Set scrollView height dynamically - iphone

I m a newbie to iphone development and this is my first question.
I m displaying a UITableView in UIScrollView and I could not specify the height for both tableView and scrollView because the data is not static and it comes from services.
I need scrollView to set its height dynamically according to the content(height)of tableView.
I have done this but I couldn't see the last cell complete data.
self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0,0,327,480) style:UITableViewStylePlain];
self.tableView.delegate=self;
self.tableView.dataSource=self;
self.tableView.scrollEnabled = NO;
[testscroll addSubview:self.tableView];
[self.tableView reloadData];
self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y, self.tableView.frame.size.width, self.tableView.contentSize.height);
float ftbl = self.tableView.frame.origin.y + self.tableView.contentSize.height + 150;
scrollView.contentSize=CGSizeMake(320, ftbl);
scrollView.scrollEnabled=YES;
Im calculating height of tableview :
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView: self.tableView cellForRowAtIndexPath: indexPath];
NSString *city = lblcity.text;
UIFont *font = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize bounds = [city sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
NSString *state = lblstate.text;
UIFont *font1 = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize1 = CGSizeMake(280.0f, MAXFLOAT);
CGSize bounds1 = [state sizeWithFont:font1 constrainedToSize:constraintSize1 lineBreakMode:NSLineBreakByWordWrapping];
NSString *name = lblname.text;
UIFont *font2 = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize2 = CGSizeMake(280.0f, MAXFLOAT);
CGSize bounds2 = [name sizeWithFont:font2 constrainedToSize:constraintSize2 lineBreakMode:NSLineBreakByWordWrapping];
NSString *address = lbladdress.text;
UIFont *font3 = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize3 = CGSizeMake(280.0f, MAXFLOAT);
CGSize bounds3 = [address sizeWithFont:font5 constrainedToSize:constraintSize3 lineBreakMode:NSLineBreakByWordWrapping];
return (CGFloat) cell.bounds.size.height + bounds.height+bounds1.height+bounds2.height+bounds3.height;
}
How can scrollView increase/decrease its height according to the height of UItableview?
EDIT:
-(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];
lblname = [[UILabel alloc] initWithFrame:CGRectZero];
lblname.tag = 111;
lblname.backgroundColor = [UIColor clearColor];
[lblname setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
[lblname setLineBreakMode:NSLineBreakByWordWrapping];
[cell addSubview:lblname];
lbladdress = [[UILabel alloc] initWithFrame:CGRectZero];
lbladdress.tag = 113;
lbladdress.backgroundColor = [UIColor clearColor];
[lbladdress setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[lbladdress setLineBreakMode:NSLineBreakByWordWrapping];
[cell addSubview: lbladdress];
lblcity = [[UILabel alloc] initWithFrame:CGRectZero];
lblcity.tag = 115;
lblcity.backgroundColor = [UIColor clearColor];
[lblcity setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[lblcity setLineBreakMode:NSLineBreakByWordWrapping];
[cell addSubview: lblcity];
lblstate=[[UILabel alloc] initWithFrame:CGRectZero];
lblstate.tag = 116;
lblstate.backgroundColor = [UIColor clearColor];
[lblstate setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[lblstate setLineBreakMode:NSLineBreakByWordWrapping];
[cell addSubview: lblstate];
}
cell.accessoryType= UITableViewCellAccessoryDetailDisclosureButton;
NSMutableDictionary *d =[[NSMutableDictionary alloc]initWithDictionary: [providerarray objectAtIndex:indexPath.row]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *name2 = [d objectForKey:#"Name"];
CGSize constraint1 = CGSizeMake(175, 2000.0f);
CGSize size1 = [name2 sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
lblname = (UILabel *)[cell viewWithTag:111];
lblname.text = [NSString stringWithFormat:#"%#",name2];
[lblname setNumberOfLines:0];
lblname.frame = CGRectMake(105,25, size1.width, size1.height);
NSString *lane2 = [d objectForKey:#"Address"];
CGSize constraint3 = CGSizeMake(175, 2000.0f);
CGSize size3 = [line2 sizeWithFont: [UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint3 lineBreakMode:NSLineBreakByWordWrapping];
lbladdress = (UILabel *)[cell viewWithTag:113];
lbladdress.text = [NSString stringWithFormat:#"%#",lane2];
[lbladdress setNumberOfLines:0];
lbladdress.frame = CGRectMake(105,lblname.frame.size.height+lblname.frame.origin.y, size3.width, size3.height);
NSString *city2 =[d objectForKey:#"City"];
NSString *trimmedString = [city2 stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#", trimmedString);
CGSize constraint5 = CGSizeMake(175, 2000.0f);
CGSize size5 = [trimmedString sizeWithFont: [UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint5 lineBreakMode:NSLineBreakByWordWrapping];
lblcity = (UILabel *)[cell viewWithTag:115];
lblcity.text = [NSString stringWithFormat:#"%#",trimmedString];
[lblcity setNumberOfLines:0];
lblcity.frame = CGRectMake(105,lbladdress.frame.size.height+lbladdress.frame.origin.y, 175, size5.height);
NSString *state1=[d objectForKey:#"State"];
CGSize constraint6=CGSizeMake(175,2000.0f);
CGSize size6=[state1 sizeWithFont:[UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint6 lineBreakMode:NSLineBreakByWordWrapping];
state=(UILabel *)[cell viewWithTag:116];
[state setText:[NSString stringWithFormat:#"%#",state1]];
state.frame=CGRectMake(105, lblcity.frame.size.height+lblcity.frame.origin.y, size6.width, size6.height);
[state setTextAlignment:NSTextAlignmentLeft];
[state sizeToFit];
return cell;
}

I would observe the table view's contentSize property and adjust your scroll view's height based on that. For example:
Suppose you have your table view. You can observe its content size like so:
[self.tableView addObserver:self forKeyPath:#"contentSize" options:0 context:NULL];
Now, you can add this method to your view controller:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
}
Inside of this method, you can add some logic to see what observed value was changed, and then adjust your scroll view's height.
if (object == self.tableView) {
if ([keyPath isEqualToString:#"contentSize"]) {
CGRect scrollViewFrame = self.scrollView.frame;
scrollViewFrame.height = self.tableView.contentSize.height;
[self.scrollView setFrame:scrollViewFrame];
}
}
Finally you can remove the observer in dealloc.
-(void)dealloc {
[self.tableView removeObserver:self forKeyPath:#"contentSize"];
}

Related

UILabels complete text not visible

I have to place two UILabels(state,zipCode) side by side i.e California 32320 in UITableView's cell.I can see them clearly when the fontsize is less.When I increase the font-size I couldnot see the last letter of state label and zipCode label is getting added.This is the code I m working on:
-(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];
state=[[UILabel alloc] initWithFrame:CGRectZero];
state.tag = 116;
state.backgroundColor = [UIColor clearColor];
[state setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[state setLineBreakMode:UILineBreakModeWordWrap];
[cell addSubview:state];
zipCode=[[UILabel alloc] initWithFrame:CGRectZero];
zipCode.tag = 121;
zipCode.backgroundColor = [UIColor clearColor];
[zipCode setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[zipCode setLineBreakMode:UILineBreakModeWordWrap];
[cell addSubview:zipCode];
}
NSString *state1=[d objectForKey:#"State"];
CGSize constraint6=CGSizeMake(175,2000.0f);
CGSize size6=[state1 sizeWithFont:[UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint6 lineBreakMode:UILineBreakModeWordWrap];
state=(UILabel *)[cell viewWithTag:116];
state.frame=CGRectMake(105, city.frame.size.height+city.frame.origin.y+5, size6.width, 10);
[state setTextAlignment:UITextAlignmentLeft];
[state setText:[d valueForKey:#"State"]];
NSString *zip = [d objectForKey:#"Zip"];
if([zip isEqualToString:#""])
{
zipCode=[[UILabel alloc]initWithFrame:CGRectMake(105, 125, 320,10)];
zipCode .font=[UIFont fontWithName:#"Helvetica" size:12];
[zipCode setTextAlignment:UITextAlignmentLeft];
zipCode.hidden=YES;
[zipCode release];
}
else
{
NSString *zip=[d objectForKey:#"Zip"];
CGSize constraint200=CGSizeMake(175,2000.0f);
CGSize size200=[zip sizeWithFont:[UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint200 lineBreakMode:UILineBreakModeWordWrap];
zipCode=(UILabel *)[cell viewWithTag:121];
zipCode.frame=CGRectMake(13+state.frame.size.width+state.frame.origin.x, city.frame.size.height+city.frame.origin.y+5, size200.width,10);
[zipCode setTextAlignment:UITextAlignmentLeft];
[zipCode setText:[d valueForKey:#"Zip"]];
zipCode.numberOfLines=0;
}
return cell;
}
Now I can see the result as
Californi 32320
But when I reduce the font-size to 10 then I can clearly see them (California 32320).But I need the font-size to be 12 only as per my requirement.
Where I m going wrong?
Use this code it will saw the label in fit to size of your label
label.adjustsFontSizeToFitWidth = YES;
Please update the Label width with some what large. And use the "setNoOfLine" property of Lable to 2. So that, it will display text in 2 lines.
Hope it will be helpful to you.
Cheers!
There is a little trick by which the label will auto resize according to your text
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,200,40)];//set your frame
testLabel.numberOfLines = 0;//Important to add this line
testLabel.font = [UIFont boldSystemFontOfSize:15];//Set your font
testLabel.text = #"Set your text here!";
[testLabel sizeToFit]; // this line will do the trick :)
The font of your state label is Helvetica-Bold, but in your sizeWithFont, the font you specified is Helvetica. Alternatively, you can just specify state.font.
Do like this,
CGFloat lLabelWidth = [yourText sizeWithFont: factLabel.font].width;
CGRect _tempFrame=yourLabel.frame;
_tempFrame.size.width=lLabelWidth;
yourLabel.frame=_tempFrame;
hope it will helps you....

iOS - UILabel inside tableview cell

I'm very much new to iphone development and strucked at a point. Actually my need is I'm displaying some results in a UITableView and I'm displaying then UILables of UITableView's cell..
How can I make the UILabel's to adjust the content according to the text. Actually text is not static .It may be changing at run time.So I need to set dynamic size to a UILabel .Ans secondly suppose if the text is null then it should not show any space and immediately the next UILabel should start .How can I make it possible ?
Here is my code..
self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0,150,320,800) style:UITableViewStylePlain];
self.tableView.delegate=self;
self.tableView.dataSource=self;
self.tableView.scrollEnabled = NO;
[self.view addSubview:self.tableView];
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(currentHtmlElement==#"3")
{
static NSString *CellIdentifier=#"Cell";
UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}
NSMutableDictionary *d = (NSMutableDictionary *) [arr2 objectAtIndex:indexPath.row];
cell.accessoryType= UITableViewCellAccessoryDetailDisclosureButton;
UILabel *name1= [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 320, 40)];
name1.font=[UIFont boldSystemFontOfSize:16];
[name1 setTextAlignment:UITextAlignmentLeft];
[name1 setText:[d valueForKey:#"Name"]];
name1.tag = 111;
[cell addSubview:name1];
[name1 release];
UILabel *codetype=[[UILabel alloc]initWithFrame:CGRectMake(10, 45, 320,15)];
codetype .font=[UIFont boldSystemFontOfSize:12];
[codetype setTextAlignment:UITextAlignmentLeft];
[codetype setText:[d valueForKey:#"Code"]];
codetype.tag=112;
[cell addSubview:codetype];
[codetype release];
UILabel *id=[[UILabel alloc]initWithFrame:CGRectMake(10, 68, 320,10)];
id .font=[UIFont fontWithName:#"arial" size:12];
[id setTextAlignment:UITextAlignmentLeft];
[id setText:[d valueForKey:#"ID"]];
id.tag=113;
[cell id ];
[id release];
UILabel *address=[[UILabel alloc]initWithFrame:CGRectMake(10, 85, 320,10)];
address .font=[UIFont fontWithName:#"arial" size:12];
[address setTextAlignment:UITextAlignmentLeft];
[address setText:[d valueForKey:#"address"]];
line2.tag=114;
[cell addSubview: address];
[address release];
UILabel *city = [[UILabel alloc]initWithFrame:CGRectMake(10, 105, 320, 10)];
city .font=[UIFont fontWithName:#"arial" size:12];
[city setTextAlignment:UITextAlignmentLeft];
[city setText:[d valueForKey:#"City"]];
city.tag=115;
[cell addSubview:city ];
[city release];
}
Here I have set all the UILabels to static size.But what I need is dynamic size.and suppose if the address label is null then it should not show any space and next label i.e city should start immediately next after id ..How is it possible?
I did this task in my code.... you can use this code and do changes according to your code....and let me know if you get any problem.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSMutableDictionary *dicNotification =[[NSMutableDictionary alloc]initWithDictionary: [myNotification objectAtIndex:indexPath.row]];
//code to get notification text height
NSString *text = [dicNotification objectForKey:#"message"];
CGSize constraint = CGSizeMake(175, 100.0f);
CGSize size = [text sizeWithFont: [UIFont fontWithName:#"Verdana" size:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
return size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//label for message
UILabel *lblMsg = [[UILabel alloc] initWithFrame:CGRectZero];
lblMsg.tag = 12;
lblMsg.backgroundColor = [UIColor clearColor];
[lblMsg setFont:[UIFont fontWithName:#"Verdana" size:12]];
[lblMsg setLineBreakMode:UILineBreakModeWordWrap];
[cell addSubview:lblMsg];
}
NSMutableDictionary *dicNotification =[[NSMutableDictionary alloc]initWithDictionary: [myNotification objectAtIndex:indexPath.row]];
//get the message height set frame height to imageView(BubbleMid & Top) & labelMSG
NSString *txt = [dicNotification objectForKey:#"message"];
CGSize constraint = CGSizeMake(175, 2000.0f);
CGSize size = [txt sizeWithFont: [UIFont fontWithName:#"Verdana" size:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
//set frame height to labelMsg
UILabel *lblMsg = (UILabel *)[cell viewWithTag:12];
lblMsg.frame = CGRectMake(15,25, 175, size.height);
[lblMsg setNumberOfLines:size.height/16];
//set labelMsg text
lblMsg.text = [dicNotification objectForKey:#"message"];
return cell;
}
The thing is that you must use heightForRowAtIndexPath. The problem is that it is called prior to cellForRowAtIndexPath, therefore the text is not in the component and you can not simply adjust the component size to the text. So, what you do is calculate the text size using a sizeWithFont.
In case of normal/standard text
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//here you get your text string
NSString* theText = ... ;
//then calculate the size. systemFontOfSize depends on your font size
//yourLabelWidth must be known and usually depends on scree size or if the tableview has an index
CGSize textSize = [theText sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(yourLabelWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
return textSize.height;
}
In the case of attributed text
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//here you get your text string
NSAttributedString* theText = ...;
//then calculate the size.
//yourLabelWidth must be known and usually depends on scree size or if the tableview has an index
CGRect rectSize = [theText boundingRectWithSize:CGSizeMake(yourLabelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:NULL];
return rectSize.size.height;
return textSize.height;
}
you can make UILable adjust content with bellow code
CGSize sizeToMakeLabel = [name1.text sizeWithFont: name1.font];
name1.frame = CGRectMake(name1.frame.origin.x, name1.frame.origin.y,
sizeToMakeLabel.width, sizeToMakeLabel.height);
and here set second lable like bellow..
UPDATE
if([[d valueForKey:#"address"] isEquelToString:#""]){
UILabel *city=[[UILabel alloc]initWithFrame:CGRectMake(10, idLable.frame.origin.y + id.frame.size.height+10 , 320,15)];
city .font=[UIFont fontWithName:#"arial" size:12];
[city setTextAlignment:UITextAlignmentLeft];
[city setText:[d valueForKey:#"City"]];
city.tag=115;
[cell addSubview:city ];
CGSize sizeToMakeLabel = [city.text sizeWithFont: city.font];
city.frame = CGRectMake(city.frame.origin.x, city.frame.origin.y,
sizeToMakeLabel.width, sizeToMakeLabel.height);
}
else{
UILabel * address =[[UILabel alloc]initWithFrame:CGRectMake(10, idLable.frame.origin.y + id.frame.size.height+10 , 320,15)];
address .font=[UIFont fontWithName:#"arial" size:12];
[address setTextAlignment:UITextAlignmentLeft];
[address setText:[d valueForKey:#"address"]];
line2.tag=114;
[cell addSubview: address];
CGSize sizeToMakeLabel = [address.text sizeWithFont: address.font];
address.frame = CGRectMake(address.frame.origin.x, address.frame.origin.y,
sizeToMakeLabel.width, sizeToMakeLabel.height);
}
and so on for every label..
follow this logic for whole label
i hope this help you...

Custom cell with overlapping cells

I´m using the method cellForRowAtIndexPath to draw cells with 2 labels. When i reuse a cell the label i had before in that cell isn´t erased, so i get two labels overlapping because i´m reusing a cell. This is weird cause only the label title gets overlapped, the other doesn´t.
So what i did to fix this, is that i´m always creating a new cell. Which isn´t appropriate but solves the problem... Anyone had a similar bug and manage to fix it? Cause i just made a workaround...
//Desenhado por codigo
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
UILabel *label = nil;
UILabel *label2 = nil;
UIColor *green = [UIColor colorWithRed:0 green: 0.77 blue:0 alpha:1];
cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
// if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"Cell"] autorelease];
//Descrição
label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setMinimumFontSize:FONT_SIZE];
[label setNumberOfLines:0];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label setFont:[UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:14.0]];
[label setTag:1];
[label setTextColor:green];
[label setBackgroundColor:[UIColor clearColor]];
label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"barra_cinza_lista.png"]];
[[cell contentView] addSubview:label];
label2 = [[UILabel alloc] initWithFrame:CGRectZero];
[label2 setLineBreakMode:UILineBreakModeWordWrap];
[label2 setMinimumFontSize:FONT_SIZE];
[label2 setNumberOfLines:0];
[label2 setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label2 setFont:[UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:14.0]];
[label2 setTag:2];
[label2 setTextColor:[UIColor whiteColor]];
[label2 setBackgroundColor:[UIColor clearColor]];
[[cell contentView] addSubview:label2];
}
NSString *text = [self getTableViewRow:tableView index:indexPath];
NSString *title = #" %#";
if(tableView == myTableView1)
title = [NSString stringWithFormat:title, [_titlesResults objectAtIndex:indexPath.row]];
else
title = [NSString stringWithFormat:title, [_titlesVision objectAtIndex:indexPath.row]];
CGFloat widthMax = CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2);
CGSize constraint = CGSizeMake(widthMax, 20000.0f); //Tamanho máximo permitido de largura e altura
CGSize size1 = [title sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; //Tamanho ocupado pelas letras
CGSize size2 = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; //Tamanho ocupado pelas letras
if (!label)
label = (UILabel*)[cell viewWithTag:1];
if (!label2)
label2 = (UILabel*)[cell viewWithTag:2];
[label setText:title];
[label setFrame:CGRectMake(0, 0, 320, MAX(size1.height, 44.0f))];
[label2 setText:text];
[label2 setFrame:CGRectMake(CELL_CONTENT_MARGIN, 3 * CELL_CONTENT_MARGIN + size1.height, widthMax, MAX(size2.height, 44.0f))];
return cell;
}
At the beginning of the method, enumerate through all the UIView objects in [cell.contentView subviews] and get rid of them, like so:
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
This works because all UI elements inherit from UIView and thus can be removed as if they were.
first, uncomment this line:
// if (cell == nil)
if you don't, you are simply creating and allocating a new cell every time you scroll, and never release the old ones...

UIButton with UIImages in a UITableViewCell - Overlapping etc

I have a problem with my UITableViewCell's. I am developing an application where certain posts in a feed may contain an image, and the button clicked will also need to contain a 'tag' number depending on which row of the table it is as I have an array of images downloaded.
The problem lies when I am scrolling (as you have already guessed) the table. The image loads fine, however when I scroll up/down the image will then go above other cells, and when the cell is shown back on the screen, the image will quickly change it's position to the proper position etc.
Here's the code for my UITableView:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [feed count];
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier
{
CGRect rect = [self.tableView bounds];
CGRect CellFrame = CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f);
CGRect TitleFrame = CGRectMake(55.0f, 10.0f, 240.0f, 15.0f);
CGRect TextFrame = CGRectMake(55.0f, 25.0f, 250.0f, 15.0f);
CGRect PinFrame = CGRectMake(21.0f, 10.0f, 30.0f, 30.0f);
CGRect ViewFrame = CGRectMake(50.0f, 35.0f, 260.0f, 0.0f);
CGRect CommentsFrame = CGRectMake(300.0f, 10.0f, 20.0f, 15.0f);
UILabel * lblTemp;
UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setFrame:CellFrame];
lblTemp = [[UILabel alloc] initWithFrame:TitleFrame];
lblTemp.tag = 1;
lblTemp.numberOfLines = 0;
lblTemp.opaque = NO;
lblTemp.font = [UIFont systemFontOfSize:13.0f];
lblTemp.backgroundColor = [UIColor clearColor];
lblTemp.textColor = [UIColor blackColor];
lblTemp.textAlignment = UITextAlignmentLeft;
lblTemp.shadowColor = [UIColor whiteColor];
lblTemp.shadowOffset = CGSizeMake(0, 1);
[cell.contentView addSubview:lblTemp];
lblTemp = [[UILabel alloc] initWithFrame:TextFrame];
lblTemp.tag = 2;
lblTemp.numberOfLines = 0;
lblTemp.lineBreakMode = UILineBreakModeWordWrap;
lblTemp.adjustsFontSizeToFitWidth = NO;
lblTemp.font = [UIFont systemFontOfSize:13.0f];
lblTemp.textColor = [UIColor lightGrayColor];
lblTemp.backgroundColor = [UIColor clearColor];
lblTemp.shadowColor = [UIColor whiteColor];
lblTemp.shadowOffset = CGSizeMake(0, 1);
[cell.contentView addSubview:lblTemp];
lblTemp = [[UILabel alloc] initWithFrame:CommentsFrame];
lblTemp.tag = 5;
lblTemp.numberOfLines = 1;
lblTemp.font = [UIFont systemFontOfSize:13.0f];
lblTemp.textColor = [UIColor lightGrayColor];
lblTemp.backgroundColor = [UIColor whiteColor];
lblTemp.shadowColor = [UIColor whiteColor];
lblTemp.shadowOffset = CGSizeMake(0, 1);
[cell.contentView addSubview:lblTemp];
UIImageView * imgTemp = [[UIImageView alloc] initWithFrame:PinFrame];
imgTemp.tag = 3;
[cell.contentView addSubview:imgTemp];
UIView * viewTemp = [[UIView alloc] initWithFrame:ViewFrame];
viewTemp.tag = 4;
[viewTemp setBackgroundColor:[UIColor whiteColor]];
[cell.contentView addSubview:viewTemp];
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = #"Cell";
UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//UITableViewCell * cell = [self getCellContentView:CellIdentifier];
if (cell == nil) {
cell = [self getCellContentView:CellIdentifier];
} else {
[cell.contentView viewWithTag:999];
}
cell.backgroundColor = [UIColor clearColor];
UILabel * title = (UILabel *)[cell viewWithTag:1];
UILabel * journey = (UILabel *)[cell viewWithTag:2];
UIImageView * pin = (UIImageView *) [cell viewWithTag:3];
UILabel * comments = (UILabel *)[cell viewWithTag:5];
title.text = [NSString stringWithFormat:#"%#", [[feed objectAtIndex:indexPath.row] objectForKey:#"comment"]];
[title sizeToFit];
title.frame = CGRectMake(title.frame.origin.x, title.frame.origin.y, 240, title.frame.size.height);
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"weather_desc"] != [NSNull null] ||
[[feed objectAtIndex:indexPath.row] objectForKey:#"weather_temp"] != [NSNull null]) {
journey.text = [NSString stringWithFormat:#"It's %# and %#°C.", [[feed objectAtIndex:indexPath.row] objectForKey:#"weather_desc"], [[feed objectAtIndex:indexPath.row] objectForKey:#"weather_temp"]];
} else {
journey.text = [NSString stringWithFormat:#"%#", [[[feed objectAtIndex:indexPath.row] objectForKey:#"journey"] objectForKey:#"name"]];
}
journey.frame = CGRectMake(journey.frame.origin.x, 10 + title.frame.size.height, 240, 15);
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"latitude"] != [NSNull null]) {
pin.image = [UIImage imageNamed:#"LocationPin.png"];
} else {
pin.image = [UIImage imageNamed:#"Pin.png"];
}
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"image_file_size"] != [NSNull null]) {
NSString * text = [NSString stringWithFormat:#"%#", [[feed objectAtIndex:indexPath.row] objectForKey:#"comment"]];
CGFloat height = [text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(250, 1500) lineBreakMode:UILineBreakModeWordWrap].height;
UIImage * myImage = [images objectForKey:[NSString stringWithFormat:#"%i", indexPath.row]];
UIButton * button = [[UIButton alloc] initWithFrame:CGRectZero];
[button setBackgroundImage:myImage forState:UIControlStateNormal];
[button setFrame:CGRectMake(title.frame.origin.x + 55.0f, 40.0f + height, 250.0f, myImage.size.height)];
[button setTag:10 + indexPath.row];
[button addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];
UIView * backView = (UIView *) [cell viewWithTag:4];
[backView setFrame:CGRectMake(title.frame.origin.x + 50.0f, 35.0f + height, 260.0f, myImage.size.height + 10.0f)];
} else {
UIView * backView = (UIView *) [cell viewWithTag:4];
[backView setFrame:CGRectZero];
[backView setBackgroundColor:[UIColor clearColor]];
}
comments.text = [NSString stringWithFormat:#"%i", [[[feed objectAtIndex:indexPath.row] objectForKey:#"comments"] count]];
UIImage * background = [UIImage imageNamed:#"CellBackground.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:background];
imageView.contentMode = UIViewContentModeScaleToFill;
[cell setBackgroundView:imageView];
return cell;
}
- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
MilestoneView * milestoneView = [[MilestoneView alloc] initWithNibName:#"MilestoneView" bundle:nil];
[milestoneView setMilestone:[feed objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:milestoneView animated:YES];
}
- (CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * text = [NSString stringWithFormat:#"%#", [[feed objectAtIndex:indexPath.row] objectForKey:#"comment"]];
CGFloat height = [text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(240, 1500) lineBreakMode:UILineBreakModeWordWrap].height;
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"image_file_size"] != [NSNull null]) {
UIImage * myImage = [images objectForKey:[NSString stringWithFormat:#"%i", indexPath.row]];
height += myImage.size.height + 15.0f;
}
return height + 37;
}
I am also using Apple's inbuilt 'ARC' with iOS 5.0.
Kind regards,
Dominic
In this code you add button in cellForRowAtIndexPath , hence this is happen....
so , you add the code for button , backView in getCellContentView and fetch images from array in getCellContentView.
UIImage *myImage = [images objectForKey:[NSString stringWithFormat:#"%i", indexPath.row]];
then,
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
[button setBackgroundImage:myImage forState:UIControlStateNormal];
[button setFrame:CGRectMake(55.0f, 40.0f, 250.0f, myImage.size.height)];
change height , width & x,y co-or. what u want and
set cell index to button.
[button setTag:indexPath.row];
[button addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
Let me know if you have any problem....
Replace following function header
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {
.
.
}
with this function
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier indexPathForButtonTag:(NSIndexPath*)indexPath {
.
.
}
Replace following line in cellForRowAtIndex
cell = [self getCellContentView:CellIdentifier];
With the
cell = [self getCellContentView:CellIdentifier indexPathForButtonTag:indexPath];
You dont need each button to have a different tag. You should not be adding any subviews to the cell in cellForRowAtIndexPath because you will inevitably end up adding subview on top of subview. I notice you are also adding an image view as the cell's background in this method - you should only do this when you are creating a new cell.
Im going to assume there is a good reason you are not using a xib file for this cell layout, so just add the button in your contentView method and give it a known tag.
In your button's action method you can find out which row of the table the button was in by using the locationInView: and indexPathForRowAtPoint: methods:
CGPoint hit = [sender locationInView:self.tableView];
NSIndexPath *hitRow = [self.tableView indexPathForRowAtPoint:hit];
Also, note that setting a view's .hidden property to YES is probably less effort that setting its frame to CGRectZero.
Ended up fixing the solution by doing the following simple code:
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview]superview]];
I used the UIButton sender to get the cell that it was within. I also pulled out all the modifications of the .tag's and kept them at the same number.

xml data in UITableview in iPhone app

how can i show the xml data in UITableView according to the attribute field of the xml data?
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *) string {
[currentElementValue appendString:string];
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(#"elementName %# %#", elementName, currentElementValue);
currentElementValue=nil;
[currentElementValue release];
}
here is some code where i am getting the element name in my xml file.now i want to display these data on a UITableView cell.
if i become unable to express the problem then please knock....
NOTE THAT: if somebody give me source code then it will better for me,because its very urgent for me.
Thanks in Advance.
Every time you parse your xml data, get that value intoone array and than display that in tableview.
#pragma mark tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
int sectionCount = [records count];
NSLog(#"section cout: %d",sectionCount);
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
cell.accessoryType = UITableViewCellSelectionStyleNone;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag =10;
[cell.contentView addSubview:cellView];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
imgView.image = [UIImage imageNamed:#"productbox.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 2.0;
imgView.tag = 5;
[cellView addSubview:imgView];
CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
idLabel.textAlignment = UITextAlignmentLeft;
idLabel.textColor = [UIColor blackColor];
idLabel.font = [UIFont systemFontOfSize:12];
idLabel.backgroundColor = [UIColor clearColor];
idLabel.layer.borderColor = [UIColor grayColor].CGColor;
idLabel.tag = 0;
CGRect statusRect = CGRectMake(65, 22, 190, 22);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
statusLabel.tag = 1;
CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
orderDate.textAlignment = UITextAlignmentLeft;
orderDate.textColor = [UIColor blackColor];
orderDate.font = [UIFont systemFontOfSize:12];
orderDate.backgroundColor = [UIColor clearColor];
orderDate.layer.borderColor = [UIColor grayColor].CGColor;
orderDate.tag = 2;
CGRect byRect = CGRectMake(65, 75, 190, 22);
byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
byLabel.textAlignment = UITextAlignmentLeft;
byLabel.textColor = [UIColor blackColor];
byLabel.font = [UIFont systemFontOfSize:12];
byLabel.backgroundColor = [UIColor clearColor];
byLabel.layer.borderColor = [UIColor grayColor].CGColor;
byLabel.tag = 3;
CGRect totalRect = CGRectMake(65, 98, 190, 22);
totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
totalLabel.textAlignment = UITextAlignmentLeft;
totalLabel.textColor = [UIColor blackColor];
totalLabel.font = [UIFont systemFontOfSize:12];
totalLabel.backgroundColor = [UIColor clearColor];
totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
totalLabel.tag = 4;
[cellView addSubview:idLabel];
[cellView addSubview:statusLabel];
[cellView addSubview:orderDate];
[cellView addSubview:byLabel];
[cellView addSubview:totalLabel];
}
cellView = (UIView *)[cell.contentView viewWithTag:10];
idLabel = (UILabel *)[cellView viewWithTag:0];
statusLabel = (UILabel *)[cellView viewWithTag:1];
orderDate = (UILabel *)[cellView viewWithTag:2];
byLabel = (UILabel *)[cellView viewWithTag:3];
totalLabel = (UILabel *)[cellView viewWithTag:4];
imgView = (UIImageView *)[cellView viewWithTag:5];
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Get the selected country
NSString *selectedSection = [ NSString stringWithFormat:#"%#",[[records objectAtIndex:indexPath.section] objectAtIndex:0] ];
dvController = [[OrderDetailsViewController alloc] initWithNibNameAndCurrentTweetUser:#"OrderDetailsViewController" bundle:nil:selectedSection];
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
dvController = nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 130;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 20)];
[v setBackgroundColor:[UIColor blackColor]];
UILabel* hdr = [[[UILabel alloc] initWithFrame:CGRectMake(10,0, tableView.bounds.size.width,20)] autorelease];
hdr.textAlignment = UITextAlignmentLeft;
hdr.font = [UIFont fontWithName:#"Arial-BoldMT" size:12];
hdr.textColor = [UIColor whiteColor];
hdr.backgroundColor = [UIColor blackColor];
[v addSubview:hdr];
hdr.text = [NSString stringWithFormat:#"Order #%#",[[records objectAtIndex:section] objectAtIndex:0]];
return v ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 20;
}