creating label on uitablview cell in iphone? - objective-c

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:

Related

How to change the bounce-region's color/background for a horizontal UITableView

I'm working on a custom "Pulse style" UITableView according to this tutorial, and everything is going great. I've made some modifications and extensions but there is one feature I'd like to implement that I need some help with: the color of the horizontal bounce regions.
This is the method that creates my cell with a table view in it:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = [#"TableViewCell" stringByAppendingFormat:#"%i", self.content.indexInArrayOfViews];
UIView *view = [self.content viewAtIndex:indexPath.row];
UITableViewCell *cell = [self.horizontalTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
view.center = CGPointMake(view.center.y,view.center.x);
view.contentMode = UIViewContentModeCenter;
view.transform = CGAffineTransformMakeRotation(M_PI_2);
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell addSubview:view];
return cell;
}
I'm aware there is a reuse cell issue, but for right now I want to change this color here [IMG].
I can control the color of the vertical table view bounce areas, but I am having difficulty replicating this success for my horizontal view.
This is how I do it vertically:
CGRect frame = self.tableView.bounds;
frame.origin.y = -frame.size.height;
UIView* topBack = [[UIView alloc] initWithFrame:frame];
topBack.backgroundColor = [self.delegate backgroundColorForTopOfTableView];
[self.tableView addSubview:topBack];
[topBack release];
This was according to this StackOverflow question.
How do I change the color/background of my horizontal table view (which is nested in a table view cell)?
Here is an album with some relevant iPhone screenshots and IB screenshots.
I discovered a solution:
if (indexPath.row == 0){
UIView *bounce = [[UIView alloc] initWithFrame:CGRectMake(-320, 0, 320, 150)];
bounce.backgroundColor = [self.delegate colorForBounceRegionAtRow:self.content.indexInArrayOfViews];
[view addSubview:bounce];
}
if (indexPath.row + 1 == self.content.viewCount){
UIView *bounce = [[UIView alloc] initWithFrame:CGRectMake([self.content widthOfViewAtIndex:self.content.viewCount - 1], 0, 320*2, [self.content greatestHeight])];
bounce.backgroundColor = [self.delegate colorForBounceRegionAtRow:self.content.indexInArrayOfViews];
[view addSubview:bounce];
}
This adds a full screen's worth of colored rectangle to the first and last elements, giving the illusion of a bounce region.

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

How do I clear a cell completely when I reuse it?

When I call [table reloaddata];
The cells get redrawn with new data, but my UILabels get messed up because they are drawn over the old UILabels, so its a mess.
static NSString* PlaceholderCellIdentifier = #"PlaceholderCell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.contentView.backgroundColor = [UIColor clearColor];
}
Is my Init of the cell.
I add a UILabel like so
UILabel *theDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 35,140, 20)];
[theDateLabel setBackgroundColor:[UIColor clearColor]];
[theDateLabel setTextColor:[UIColor lightGrayColor]];
[theDateLabel setText:[dateFormatter stringFromDate:theDate]];
[theDateLabel setFont:[UIFont fontWithName:#"TrebuchetMS-Bold" size:15]];
[cell addSubview:theDateLabel];
[theDateLabel release];
There are a few more labels in the cell, same thing.
What I would like to happen is that the old labels disappear from the cell so that they are no longer visible.
You should not add theDateLabel as a subview of cell. You should add it as a subview of cell.contentView.
As yuji suggests, one way to implement this is to create a subclass of UITableViewCell with a property for each custom subview. That way you can easily get to the date label of a reused cell to set its text for the new row.
Another common approach is to use the tag property that every UIView has. For example:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* PlaceholderCellIdentifier = #"PlaceholderCell";
static const int DateLabelTag = 1;
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:PlaceholderCellIdentifier] autorelease];
UILabel *theDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 35,140, 20)];
theDateLabel.tag = DateLabelTag;
theDateLabel.backgroundColor = [UIColor clearColor];
theDateLabel.textColor = [UIColor lightGrayColor];
theDateLabel.font = [UIFont fontWithName:#"TrebuchetMS-Bold" size:15];
[cell.contentView addSubview:theDateLabel];
[theDateLabel release];
}
NSDate *theDate = [self dateForRowAtIndexPath:indexPath];
UILabel *theDateLabel = [cell.contentView viewWithTag:DateLabelTag];
theDateLabel.text = [dateFormatter stringFromDate:theDate];
return cell;
}
While Richard's solution will work, if your cells have any other subviews they'll get removed as well. Also, allocating and initializing your subviews every time you draw a cell isn't necessarily optimal.
The standard solution here is to create a subclass of UITableViewCell with a property #dateLabel (and so on for the other labels). Then, when you're initializing a cell, if it doesn't have a #dateLabel yet you can give it a new one, otherwise you only have to set its text.

Programmatically Add Image to TableView Cell

I have a UITableView that gets information from a server and publishes the data into a table view. Inside of each cell is the information from the server.
For the purpose of this example, let's say the information we get from the server are numbers: 1, 2, 3, 4.
What I want to do is add an image (programmatically because there are if statements involved, etc) to the left side of the cell, and the text (1, 2, etc) right next to it.
Basically, I want each cell to look like this:
_____________________________________
| (IMAGE) (TEXT) | --CELL 0
--------------------------------------
_____________________________________
| (IMAGE) 2 | --CELL 1
--------------------------------------
Please excuse my crude illustration. :)
here you go:
cell.imageView.image = [UIImage imageNamed:#"image.png"];
Swift:
cell.imageView?.image = UIImage(named: "image.png")
You can add both the image and the text to the UITableViewCell in your UITableViewController subclass like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[[cell imageView] setImage:anImage];
[[cell textLabel] setText:[NSString stringWithFormat:#"%d",[indexPath row]];
return cell;
}
There are a few "built-in" properties to UITableViewCell that you can take advantage of, such as the imageView, textLabel, and detailTextLabel. For more information, check out the Table View Programming Guide.
The Swift 2.0 version of the first answer is:
cell.imageView?.image = UIImage(named: "image.png")
UITableViewCell objects have an imageView property; you can just set this image view's image and it will automatically display the image in the right place with the title next to it.
// create a rectangle box for image view
UIImageView *iconImage = [[UIImageView alloc] init];
iconImage.frame = CGRectMake(12,4,53.5,53.5);
// Create a label for cells
UILabel *cellName = [[UILabel alloc] initWithFrame:CGRectMake(75,18,200,20)];
cellName.font = [self fontForBodyTextStyle];
NSString *cellNameStr = [NSString stringWithFormat:#"%#",self.tableCellNames[indexPath.row]];
// Select path row tab actions
switch (indexPath.row) {
case 0:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"condition.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 1:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"videos.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 2:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"provider.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 3:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"info.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
default:
NSAssert(NO, #"Unhandled value in cellForRowAtIndexPath");
break;
}

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;
}