Set Multiple UILabel in a row of UITable - objective-c

I want to set UILabel in row of table, but the issue is that the number of label each time is different when the app restarts.
Clear that more detail that I want to create a table which has dynamic row and column. Rows are set themselves, but in the column i set the label which is also dynamics, so how can i set that label each time of new web service will call ?
Ex.
row/column
A1 b11 b12 .......b1n
A2 b21 b22 .......b2n
A3 b31 b32 .......b3n
.
.
Am bm1 bm2 .......bmn
where A is row or b is column

You could have a mutable array called rowData for example. In your init/initWithCoder/etc method, you could create another mutable array called columnData for example that could contain the data for each label. Add a columnData object for each row to rowData.
For your cellForRowAtIndexPath method, you could do something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"] autorelease];
int row = [indexPath row];
int i = 0;
int nLabels = [[rowData objectAtIndex:row] count];
UILabel *label;
NSLog([NSString stringWithFormat:#"%d labels", nLabels]);
for (i = 0; i < nLabels; i++) {
NSLog([NSString stringWithFormat:#"%d", i]);
label = [[[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x + (i * 40), cell.frame.origin.y, 40, cell.frame.size.height)] autorelease]; //replace 40 with desired label width
label.textColor = [UIColor grayColor];
label.backgroundColor = [UIColor clearColor];
// set the label text here
[cell.contentView addSubview:label];
NSLog([NSString stringWithFormat:#"%d subviews", [[cell.contentView subviews] count]]);
}
}
return cell;
}

Better option would be just create a UITableView in UITableViewCell and your each label would be cell and you can disable inner tableview scrolling. But you need to make sure that you have calculated inner tableview height properly.
Other solution like adding n number of UIlabel etc wont give you smooth scrolling.

Create cells that have the maximum number of labels you might need. Make their tag be 1,2,3,4... - increasing numbers. Each time you are asked to supply a cell by the table, you either take an old one or new one, decide how many labels you need, make that range of labels visible (ie label.hidden = NO;), then hide the other labels. You will need to change the text of the visible labels obviously.

You use tag method and indexpath.row.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
for (i = 0; i < n; i++) {
label = [[UILabel alloc] initWithFrame:CGRectMake (i * yourWidth, 0, yourWidth + 5, yourHight)];
label.textColor = [UIColor blueColor];
label.tag = (indexPath.row)*100 + i //you can create n labels in a row.
label.text = [NSString stringWithString:#"%d",label.tag];
[cell.contentView addSubview:label];
}
}
return cell;
}
I think it will be helpful to you.

You should consider using a different view, such as DTGridView

Related

UITableView overlaps cells after scrolling

All, I have a UITableView to which I add cells on user input. My cells have a slight transparency, and I recently noticed that after I have more cells than fit the screen, when I scroll down and back up, the cells which were momentarily off-screen now have new cells positioned behind them!
This shows up in my app, and also is evidenced in the view hierarchy debugger.
Interesting to note that it only happens when two or more cells scroll off screen (notice the count skips cell 7, which is at the bottom, just off the screen at the moment.
I figure this has something to do with caching the UIScrollView data for quicker loads? How do I stop it?
Adding a cell:
NSArray *indexPaths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:numberOfCounters inSection:0], nil];
[counterTable insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom];
numberOfCounters++;
[counters addObject:[[CKCounter alloc] init]];
cellForRowAtIndexPath: method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"CKCounter";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
CKCounter *counter = [counters objectAtIndex:indexPath.row];
[counter setCurrentCount:indexPath.row];
[counter setIndex:indexPath.row];
[cell.contentView addSubview:[counter view]];
[cell.contentView setAutoresizesSubviews:TRUE];
[cell setBackgroundColor:[UIColor clearColor]];
/** Sets up the bounds for the subcounters **/
CGRect frame = cell.contentView.bounds;
frame.size.height -= counterMargins; // This will give the counters an inset
frame.size.width -= counterMargins; // The gap will be split to each side
frame.origin = cell.contentView.bounds.origin;
counter.view.frame = frame;
counter.view.opaque = false;
counter.view.center = cell.contentView.center;
//[NSString stringWithFormat:#"%lu", (unsigned long)[indexPath indexAtPosition:0]]
return cell;
}
See also: This Question

creating label on uitablview cell in iphone?

I am new to iPhone devlopemnt I am developing one app. In that app I need show list items with their respective prices in an UITableView. To solve this problem I am following some concept like creating label dynamically in UITableViewCell to show the items and their prices.
In app the first indexid == 1 means that I am showing list places on click of particular cell on list am geting list of favorite items with prices that means indexid = 2 ...on click of back button indexid = 1 then i need hide that label ...but label is not hideing it show list prices not list of items
lblText.text = nil;
btnBack.hidden = FALSE;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
cell.textLabel.highlightedTextColor = [UIColor orangeColor];
}
///////////////////// Cell Title /////////////////////
if (indexId == 1)
{
// NSLog(#"%#",lblText1);
cell.textLabel.text = [NSString stringWithFormat:#"%#", [test.arrTitle objectAtIndex:indexPath.row]];
lblText = [[UILabel alloc] initWithFrame:CGRectMake(250, 7, 40, 30)]; // For right alignment
lblText.text = [test.arrId objectAtIndex:indexPath.row];
[lblText setTextAlignment:UITextAlignmentCenter];
lblText.textColor = [UIColor redColor];
lblText.backgroundColor = [UIColor clearColor];
[cell addSubview:lblText];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"products-category-bg.png"]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[lblText release];
}
else
{
lblText.hidden = YES;
cell.textLabel.text = [NSString stringWithFormat:#" %#", [test.arrTitle objectAtIndex:indexPath.row]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"product-bg-hover.png"]];
}
return cell;
}
I have the following problem. The label is creating ok, but after on click of back button, I get label values in main tableview.
How can I release the label object with data ?
thanks & regards
Please help me out of this problem
Your code looks fine to me, just replace one line in above code with the link written below
[cell.contentView addSubview:lblText];
Instead
[cell addSubview:lblText];
Hope It will resolve your issue.
If you're using the same table view instance for the different states in your application you're also re-using cells that were created previously:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
With each cell, when the indexid == 1 you're also doing this:
[cell addSubview:lblText];
To me, this says that each cell you've created (and that will be re-used) has a UILabel added as a subview. To truly re-use that cell you need to remove that UILabel before your logic says that you need to add it again. Not only will this remove the cells when you don't need them, it will also prevent you from adding extra UILabel instances to the cell at runtime. Try adding the code below before you check indexid
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
cell.textLabel.highlightedTextColor = [UIColor orangeColor];
}
// Be sure to remove the UILabels on the re-used cell.
for(UIView *view in cell.subviews)
if ([view isKindOfClass:([UILabel class])])
[view removeFromSuperview];
if (indexid == 1) { ....
This will remove the UILabel each time the cell is created allowing you to conditionally re-added it as a subview.
Try to set a tag to your label(will help you to set data to labels, you can get the label by calling
[cell viewWithTag:theLabelTag]
where theLabelTag tag can be the index)
and set the label value in
tableView: willDisplayCell: forRowAtIndexPath:
instead of
tableView: cellForRowAtIndexPath:

IOS UITableViewCell Spacer (or margin)

I'm trying to get a space between my table custom view cells on my table view controller. For example, for each cell created it is stacked up one by one and there is no margin. For example on the facebook iPhone app has a spacer after each cell which i would like to create, any ideas guys?
Edit: From comment below
The code looks like this
MSRSalesCompanyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.backgroundView = [[CustomCellBackground alloc] init];
NSDictionary *company = [companies objectAtIndex:[indexPath row]];
cell.companyName.text = [company objectForKey:#"Name"];
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView.bounds = CGRectMake(0, 0, 320, 55);
[self loadImageAsync:cell withImageUrl:imageURL];
Check my answer for the similar question, it suggests you to create the invisible cells between the cells you want to divide with some space.
Option 2 is to create only the visible cells, make their height above the visible area and prepare special content and selected view's, note the selected view creation is not so easy and you'll need to do it as you probably don't want the spacing area to get selected, so i'm using the first option when there's a need to get some cell's spacing.
The main (and probably the only) disadvantage of the first option is that you have to treat the cell's indexes in a special way to distinguish the spacing-cells and the visible-cells.
If your tableView's rowHeight is 50 points, make your background image view height say, 40 points, and centre it in the cell. Then make your cell background colour [UIcolor clearColor]
Okayy i did some thing like this.....
First the BGColor Of view which will hold the Tableview is set to White (it was a personal choice w.r.t to my design) and then the cellForRowAtIndexPath method looks some thing like this.
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell = nil;
//Create Cell
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
//Retrive Values From DB
DBTable_Description *dbObject = [[DBTable_Description alloc]init];
dbObject = [contentList objectAtIndex:[indexPath row]];
//Cell View
UIView *cellView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 65)];
//ImageView
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(4.0, 8.0, 300.0, 58.0)];
imageView.userInteractionEnabled = NO;
imageView.image = imgForCellBkg;
//Label
UILabel *lblFor = [[UILabel alloc]initWithFrame:CGRectMake(70, 25, 200, 21)];
lblFor.text =dbObject.field1;
lblFor.backgroundColor = [UIColor clearColor];
lblFor.font = [UIFont fontWithName:#"Helvetica Neue" size:16];
lblFor.textColor = [UIColor grayColor];
lblFor.shadowColor = [UIColor grayColor];
//Adding Views to Cell View
[cellView addSubview:imageView];
[cellView addSubview:lblFor];
[cell.contentView addSubview:cellView];
cell.selectionStyle = NO;
return cell;
}
Okay First and formost neglect the Database code.
Now what i did is i created a View on each Cell name cellView (set the height as per ur requirement) next i had an Image View and set the appropriate image (again it may not be the thing u want to do) but pay attention to the CGRectMake i se the values according to the amount of gap i want b.w my cells.. the rest is usual.
here is the image of the view i had in my App
Let me Know if it worked
Cheers
W

Problems with UITableViewCell heights with a UILabel and random text lengths

I'm currently trying to get a UITableView to use custom cell heights based on text in an array. The problem I'm seeing is that the text seems to squish together at point rather than filling the full length of a custom cell. This results in the text overlapping over cells, sometimes disappearing under them.
Here's the code I have for determining the cell height, I'm not sure of the standard UILabel text height but this seemed to work well at the height I for the font.
if (indexPath.section == 0) {
NSString *text = [[self.recipeDict objectForKey:#"Ingredients"] objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = size.height;
return height + 20;
}
Also just in case the creation of the cells is either a hinderance to my problem or just helps you know what's going on, here's that too.
UITableViewCell *cell;
UITableViewCell *ingredientCell;
UITableViewCell *methodCell;
if (indexPath.section == 0) {
UILabel *ingredientText;
static NSString *ingredientCellIdentifier = #"Ingredient Cell";
ingredientCell = [tableView dequeueReusableCellWithIdentifier: ingredientCellIdentifier];
if (ingredientCell == nil)
{
ingredientCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: ingredientCellIdentifier] autorelease];
ingredientText = [[UILabel alloc] initWithFrame:CGRectMake(15, 7, 290, 44)];
[ingredientText setLineBreakMode:UILineBreakModeWordWrap];
[ingredientText setNumberOfLines:0];
[ingredientCell.contentView addSubview:ingredientText];
ingredientText.tag = 1;
[ingredientText release];
ingredientCell.contentMode = UIViewContentModeRedraw;
}
ingredientText = (UILabel*)[ingredientCell viewWithTag:1];
ingredientText.text = [[self.recipeDict objectForKey:#"Ingredients"] objectAtIndex: indexPath.row];
[ingredientText sizeToFit];
return ingredientCell;
}
This is my second attempt at solving this issue but it seems to be beyond my current ability so I welcome wisdom gained through experience.
UPDATE -
After further investigation it seems that the UILabel ingredientText being resized is causing the issue.
It starts out as tall as it needs to be for the text shown, however when that label is redrawn with a larger height for another piece of text which requires more lines it's never shrunk down again. It seems that the sizeToFit method is prioritising using the available height rather than taking up the width and shrinking the height.
Right now I've set the width again after the sizeToFit which works around the issue but it leads to odd spacing depending on the height of the label.
A couple of things:
You have not set the font for the UILabel, which means you're sizing to an unknown height
You need to set your UILabel autoresizing mask, so that it sizes when the cell height changes
Here is working code (tested):
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
NSString *text = [_items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = size.height;
return height + 20;
}
return tableView.rowHeight;
}
#pragma mark - UITableViewDatasource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
UITableViewCell *ingredientCell = nil;
UITableViewCell *methodCell;
if (indexPath.section == 0) {
UILabel *ingredientText;
static NSString *ingredientCellIdentifier = #"Ingredient Cell";
ingredientCell = [tableView dequeueReusableCellWithIdentifier: ingredientCellIdentifier];
if (ingredientCell == nil)
{
ingredientCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: ingredientCellIdentifier] autorelease];
ingredientText = [[UILabel alloc] initWithFrame:ingredientCell.bounds];
ingredientText.font = [UIFont systemFontOfSize:12.0f];
ingredientText.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[ingredientText setLineBreakMode:UILineBreakModeWordWrap];
[ingredientText setNumberOfLines:0];
[ingredientCell.contentView addSubview:ingredientText];
ingredientText.tag = 1;
[ingredientText release];
ingredientCell.contentMode = UIViewContentModeRedraw;
}
ingredientText = (UILabel*)[ingredientCell viewWithTag:1];
ingredientText.text = [_items objectAtIndex: indexPath.row];
return ingredientCell;
}
}
Be sure you are always be returning a values for tableView:cellForRowAtIndexPath: and tableView:heightForRowAtIndexPath: methods
The solution to this issue was that the width specified in the constant in the cell height method didn't match the frame for the cell text specified later in the cellForRowAtIndexPath method.
Once these are the same the problem resolves itself.
The different constant size led to inconsistent and inaccurate UILabel heights being reported. This led to incorrect table row heights being set.

How can i put label into the table cell?

this is the cell i want to make the left side is cell.text and the right part is label.
Now the table style is
UITableViewStyleGrouped When i try to make the label i write these codes.
cell.textLabel.text = #"All";
UIView* view = cell.contentView;
UILabel* label1 = [[UILabel alloc] initWithFrame:cell.frame];
label1.textColor = [UIColor blackColor];
label1.textAlignment = UITextAlignmentCenter;
label1.text = #"%15";
[view addSubview:label1];
[label1 release];
But this doesnt work because cell of the label cover one and another.Can any one help me to make this kind of look with code of course.
The problem in your code seems to be the label1's frame. Change the its frame like the following.
CGRect lFrame = CGRectMake(cell.frame.width - 100, 0, 100, cell.frame.height);
UILabel* label1 = [[UILabel alloc] initWithFrame:lFrame];
Using exisiting style: The style you are using is already predefined. No need to add your custom label to the cell. You can achieve this style by specifying table cell's style to UITableViewCellStyleValue1.
[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 ....
You can change the font properties like style, color and size of the cell's textLabel and detailedTextLabel to fit your needs.
Just make your UITableviewCell type to UITableViewCellStyleValue1 and do like below.
cell.textLabel.text = #"All";
cell.detailTextLabel.text = #"%15";
You don't need to add view in the cell at all. Also, you can change textLable and DetailTextLabel properties whatever you want as you change with UILabel. They are UILabel itself. So you can do everything whatever you can do with UILabel.
Hope this help.
The pre-defined styles are great if they cover your needs.
Otherwise an approach like this one will work for cases where you want more power over the layout, or more views in the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self makeCell: CellIdentifier];
}
MyData *data = [self.data objectAtIndex:indexPath.row];
UILabel *lbl1 = (UILabel *)[cell viewWithTag:1];
UILabel *lbl2 = (UILabel *)[cell viewWithTag:2];
lbl1.text = data.text;
lbl2.text = data.auxText;
return cell;
}
- (UITableViewCell *)makeLensListCell: (NSString *)identifier
{
CGRect lbl1Frame = CGRectMake(10, 0, 140, 25);
CGRect lbl2Frame = CGRectMake(10, 150, 140, 25);
UILabel *lbl;
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
// Label with tag 1.
lbl = [[UILabel alloc] initWithFrame:lbl1Frame];
lbl.tag = 1;
[cell.contentView addSubview:lbl];
[lbl release];
// Label with tag 2.
lbl = [[UILabel alloc] initWithFrame:lbl2Frame];
lbl.tag = 2;
lbl.textColor = [UIColor lightGrayColor];
[cell.contentView addSubview:lbl];
[lbl release];
// Add as many labels and other views as you like
return cell;
}