I have created an app with a table view. Which uses a view and a label in each cell. But if I create the views and cells in the (!cell) code it returns empty cells and if I remove the (!cell) condition it displays the data but does not take dynamic height. Can anyone please help me.
- (void)viewDidLoad{
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist", LanguageFile]];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:DataPath];
self.reloadArray = [tempDict objectForKey:#"Rows"];}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.reloadArray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Get data for the current row
NSString *textData = [reloadArray objectAtIndex:indexPath.section]
CGFloat dataTextHeight = [self getLabelHeightForIndex:textData];
if(dataTextHeight < 44)
{
dataTextHeight = 44;
}
return dataTextHeight;
}
-(CGFloat)getLabelHeightForIndex:(NSString *)string
{
CGSize maximumSize = CGSizeMake(280, 10000);
CGSize labelHeightSize = [string sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0f] constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelHeightSize.height < 44){
labelHeightSize.height = 44;
}
return labelHeightSize.height;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
static const int textViewTag = 1, textLabelTag = 2;
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"standard_back.png"]];
img.frame = tableView.frame;
tableView.backgroundView = img;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// First view
UIView *textView = [[UIView alloc] initWithFrame: CGRectMake(0.0, 0.0, 280.0, 36.00)];
textView.tag = textViewTag;
textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[cell.contentView addSubview:textView];
// First label
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 270.0, 36.00)];
textLabel.tag = textLabelTag;
textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:14.0f];
textLabel.textColor = [UIColor whiteColor];
textLabel.backgroundColor = [UIColor clearColor];
textLabel.numberOfLines = 0;
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// textLabel.clipsToBounds = YES;
[cell.contentView addSubview:textLabel];
}
NSString *textData = [reloadArray objectAtIndex:(indexPath.section)];
CGFloat dataTextHeight = [self getLabelHeightForIndex:textData];
UIView *textView = [cell.contentView viewWithTag:textViewTag];
CGRect textViewFrame = textView.frame;
textView.frame = CGRectMake(0.0, 0.0, textViewFrame.size.width, dataTextHeight);
UILabel *textLabel = [cell.contentView viewWithTag:textLabelTag];
CGRect textLabelFrame = textLabel.frame;
textLabel.frame = CGRectMake(10.0, 0.0, textLabelFrame.size.width, dataTextHeight);
textLabel.text = textData;
textLabel.backgroundColor= [UIColor clearColor];
textLabel.textAlignment = NSTextAlignmentCenter;
cell.backgroundColor = [UIColor colorWithWhite:0 alpha:.65];
cell.textLabel.numberOfLines = 0; // Multiline
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
return cell;
}
Thanks in advance.
I saw a lot of solutions but all was wrong or uncomplet.
You can solve all problems with 5 lines in viewDidLoad and autolayout.
This for objetive C:
_tableView.delegate = self;
_tableView.dataSource = self;
self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;
For swift 2.0:
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
Now create your cell with xib or into tableview in your Storyboard
With this you no need implement nothing more or override. (Don forget number os lines 0) and the bottom label (constrain) downgrade "Content Hugging Priority -- Vertical to 250"
You can donwload the code in the next url:
https://github.com/jposes22/exampleTableCellCustomHeight
References: http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/
This is a part of my code which i used in my app. It works for me fine.Ping me if u need help.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
CGSize constraintSize = {230.0, 20000}; //230 is cell width & 20000 is max height for cell
CGSize neededSize = [ [NSString stringWithFormat:#"%#",[cellar objectAtIndex:indexPath.row]] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Medium" size:15.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap];
return MAX(45, neededSize.height +33);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
{ cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
CGSize constraintSize = {230.0, 20000};
UILabel* label = [[UILabel alloc] init];
[label setNumberOfLines:0];
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont fontWithName:#"HelveticaNeue-Medium" size:15.0f]];
label.adjustsFontSizeToFitWidth = NO;
CGSize neededSize = [ [NSString stringWithFormat:#"%#",[cellar objectAtIndex:indexPath.row] ] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Medium" size:15.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap];
// NSLog(#"Height%f",neededSize.height);
//NSLog(#"width%f",neededSize.width);
[label setText:[NSString stringWithFormat:#"%#",[cellar objectAtIndex:indexPath.row] ]];
[label setFrame:CGRectMake(10, 2, 230, MAX(neededSize.height+30, 44.0f))];
[[cell contentView] addSubview:label];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}
Hope it helps.!!!
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return "your content height";
}
Related
I need to create a simple chat view in which i can show messages from two ends (sender and receiver) like any Message App .
What i have done till now is , created a UITableView , A UIButton and a UITextField. And on that UIButton tap , i am adding UITextField text to array , Now I need the second end also like in ours Messaging app (sender side).
Left side is receiver and Right side is sender.
My app till now looks like
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
messageLabel = nil;
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
messageLabel = [[UILabel alloc] init];
messageLabel.tag = 101;
[cell.contentView addSubview: messageLabel];
} else {
messageLabel = (UILabel*)[cell.contentView viewWithTag: 101];
} //---calculate the height for the label---
int labelHeight = [self labelHeight:[listOfMessages objectAtIndex:indexPath.row]];
labelHeight -= bubbleFragment_height;
if (labelHeight<0) labelHeight = 0;
messageLabel.frame =
CGRectMake(bubble_x + 10, bubble_y + 5,
(bubbleFragment_width * 3) - 25,
(bubbleFragment_height * 2) + labelHeight - 10);
messageLabel.font = [UIFont systemFontOfSize:15];
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.textColor = [UIColor darkTextColor];
messageLabel.backgroundColor = [UIColor greenColor];
messageLabel.numberOfLines = 0;
messageLabel.layer.cornerRadius = 8;
messageLabel.layer.masksToBounds = YES;
messageLabel.text = [listOfMessages objectAtIndex:indexPath.row];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(void) sendAction:(id) sender {
[listOfMessages addObject:field.text];
[chatTable reloadData];
field.text = #"";
[field resignFirstResponder];
}
You can take two different custom cells one for the sender and one for the receiver like this:
for Sender
for Receiver
Now, in your app, there must be login and sign-up process as it is a chat app and there will be server associated with your app to save data.
What you can do is that, when you send the message, also send the name of the receiver with it and store it in your database.
Now, in your chat view, fetch all the message data, along with the receiver names.
Fetch the userName who is currently logged in during the Login process.
You can do something like this in your cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *myArrayElement = [arr_receiverUserName objectAtIndex:indexPath.row];
//do something useful with myArrayElement
if(![myArrayElement isEqualToString:userName])
{
/// These are my messages.
//// Pop up 'mycell' here
UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
lbl_myText.minimumScaleFactor = FONT_SIZE;
[lbl_myText setNumberOfLines:0];
lbl_myText.textAlignment = NSTextAlignmentRight;
[lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSString *text = [arr_text objectAtIndex:indexPath.row];
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
// Checks if text is multi-line
if (size.width > lbl_myText.bounds.size.width)
{
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
[lbl_myText setText:text];
[lbl_myText setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_myImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
else
{
lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_myImage.frame.size.width - 18,18);
lbl_myText.textAlignment = NSTextAlignmentRight;
[lbl_myText setText:text];
}
//lbl_myText.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:lbl_myText];
}
else
{
//// These are the messages sent by some one else
/// Pop up `someonecell` here
UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
lbl_myText.minimumScaleFactor = FONT_SIZE;
[lbl_myText setNumberOfLines:0];
lbl_myText.textAlignment = NSTextAlignmentLeft;
[lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSString *text = [arr_text objectAtIndex:indexPath.row];
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
// Checks if text is multi-line
if (size.width > lbl_myText.bounds.size.width)
{
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
[lbl_myText setText:text];
[lbl_myText setFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_someoneImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
else
{
lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 18,18);
lbl_myText.textAlignment = NSTextAlignmentLeft;
[lbl_myText setText:text];
}
//lbl_myText.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:lbl_myText];
}
You can do similar things for images and audios.
For Dynamic Height Of The Cell:
To make to the height of your cell according to your UILabels, refer to Increase the main tableview row height according to the custom cell
You need to create multiple cell with different CellIdentifier For Example. Cell For sender and receiver. And you can subdivide it in categories like text,audio,video,image.
Download sample ChatUI Demo (Objective-C & Swift) from here
Lets have example for the text chat.
First of all you need to create 2 cell prototypes in your Storyboard or XIB with different CellIdentifier for example "cellSender" and "cellReceiver".
Take UILabel or UITextView inside cell and for cellSender make left alignment and for cellReceiver make the alignment right for making different layout for sender and receiver.
Then You can do with following with your code...
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BOOL sender = NO;
// Check for the sender or receiver
<code for checking message is from sender or receiver>
static NSString *CellIdentifier = sender?#"cellSender":#"cellReceiver";
messageLabel = nil;
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
messageLabel = [[UILabel alloc] init];
messageLabel.tag = 101;
[cell.contentView addSubview: messageLabel];
} else {
messageLabel = (UILabel*)[cell.contentView viewWithTag: 101];
} //---calculate the height for the label---
int labelHeight = [self labelHeight:[listOfMessages objectAtIndex:indexPath.row]];
labelHeight -= bubbleFragment_height;
if (labelHeight<0) labelHeight = 0;
messageLabel.frame =
CGRectMake(bubble_x + 10, bubble_y + 5,
(bubbleFragment_width * 3) - 25,
(bubbleFragment_height * 2) + labelHeight - 10);
messageLabel.font = [UIFont systemFontOfSize:15];
messageLabel.textAlignment = NSTextAlignmentLeft;
messageLabel.textColor = [UIColor darkTextColor];
messageLabel.backgroundColor = sender? [UIColor greenColor]: [UIColor lightGrayColor];
messageLabel.numberOfLines = 0;
messageLabel.layer.cornerRadius = 8;
messageLabel.layer.masksToBounds = YES;
messageLabel.text = [listOfMessages objectAtIndex:indexPath.row];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
EDIT
I'm using custom UITableViewCell and I Have UILabel Inside my cell but the problem is when i'm set Text To my UILabel The text destined to top .
This Is my Code :
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"EventsTBC";
EventsTBC *cell = (EventsTBC *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"EventsTBC" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.EventText.numberOfLines = 0;
cell.EventText.font = [self fontForCell];
cell.EventText.textAlignment = NSTextAlignmentRight;
// [cell.EventText setFrame:CGRectMake(-30, 30, 300, [[Tools alloc] heightForText:[[Tools alloc] warpText:[Events objectAtIndex:indexPath.row]]])];
[cell.EventText setLineBreakMode:NSLineBreakByWordWrapping];
cell.EventText.text = [[Tools alloc] warpText:[Events objectAtIndex:indexPath.row]];
cell.EventText = [self sizeToMultiline:cell.EventText];
cell.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.10];
return cell;
}
- (UIFont *)fontForCell
{
return [UIFont boldSystemFontOfSize:18.0];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// return 150;
return [[Tools alloc] heightForText:[[Tools alloc] warpText:[Events objectAtIndex:indexPath.row]]];
}
heightForText Method Gave my A height of my Text :
- (CGFloat)heightForText:(NSString *)bodyText
{
UIFont *cellFont = [UIFont systemFontOfSize:17];
CGSize constraintSize = CGSizeMake(300, MAXFLOAT);
CGSize labelSize = [bodyText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = labelSize.height;
NSLog(#"height=%f", height);
return height;
}
warpText Method Replace \n With \n To make new line .
When you print the height value, does it seem incorrect?
The sizeWithFont method was deprecated lately, and for me it stopped working.
I replaced it with something like this, thanks to another answer in this website:
NSAttributedString *attributedText = [[NSAttributedString alloc]
initWithString:bodyText
attributes:#
{ NSFontAttributeName: cellFont}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){300, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGFloat height = rect.size.height;
I am creating a Iphone app with UITableView. In that I want to change the cell size with respect to text. I used the following code. But it fails.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// CGRect screenBounds = [[UIScreen mainScreen] bounds];
// CGSize screenSize = screenBounds.size;
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:[message objectAtIndex:0]];
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:aString];
CGRect textRect = [calculationView.text boundingRectWithSize:self.view.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:calculationView.font} context:ctx];
// CGSize size = [calculationView sizeThatFits:CGSizeMake(screenSize.width, FLT_MAX)];
return textRect.size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
[cell.textLabel setLineBreakMode:NSLineBreakByWordWrapping];
[cell.textLabel sizeToFit];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.imageView.image = [UIImage imageNamed:#"gg.jpg"];
cell.textLabel.text = [NSString stringWithFormat:[message objectAtIndex:0], indexPath.row];
return cell;
}
Thanks in advance.
first you need to get text size.. and according this size you can set cell height.. like this example
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize contsize={260.00f,3000.00f};
UIFont *font=[UIFont fontWithName:#"Open Sans" size:15.0];
NSString *strt11=#"comment_text"
CGSize fontSize=[test sizeWithFont:font constrainedToSize:contsize lineBreakMode:NSLineBreakByWordWrapping];
if (fontSize.height>22)
return fontSize.height+60.0f;
return 80.0f;
}
and also put this code in cellForRowAtIndexPath method for set uilabel height..
Please use the below code.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [array_loaddata objectAtIndex:indexPath.row] ;
UIFont *font = [UIFont systemFontOfSize:10];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){kWIDTH_FOR_MESSAGE_LABEL, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return rect.size.height + 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier =[NSString stringWithFormat:#"Cell%d",indexPath.row] ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
NSString *text = [array_loaddata objectAtIndex:indexPath.row] ;
UIFont *font = [UIFont systemFontOfSize:10];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [text boundingRectWithSize:(CGSize){kWIDTH_FOR_MESSAGE_LABEL, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(46, 0,kWIDTH_FOR_MESSAGE_LABEL, rect.size.height)];
label.numberOfLines = 0;
label.textColor = [UIColor grayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text = (text ? text : #"");
label.font = font;
label.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:label];
[label release];
}
As Simple as that :
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
I'm implementing a tableView with section index. where my tableViewCells are overlapping whenever the rows are more than one in any particular section.
Here is my code.
![- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return \[self.keys count\];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
// return \[\[\[UILocalizedIndexedCollation currentCollation\] sectionTitles\] objectAtIndex:section\];
return \[keys objectAtIndex:section\];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
// return \[\[UILocalizedIndexedCollation currentCollation\] sectionIndexTitles\];
return keys;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return \[\[UILocalizedIndexedCollation currentCollation\] sectionForSectionIndexTitleAtIndex:index\];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = \[tableView dequeueReusableCellWithIdentifier:nil\];
if (cell == nil) {
cell = \[\[UITableViewCell alloc\] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier\];
}
\[self.exhibitorTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)\];
UIView* bgview = \[\[UIView alloc\] initWithFrame:CGRectMake(0, 0, 1, 1)\];
bgview.opaque = YES;
bgview.backgroundColor = \[UIColor colorWithRed:244.0f/255 green:245.0f/255 blue:246.0f/255 alpha:1.0\];
\[cell setBackgroundView:bgview\];
cell.textLabel.font = \[UIFont fontWithName:#"Roboto-Light" size:17\];
cell.detailTextLabel.font = \[UIFont fontWithName:#"Roboto-Light" size:13\];
cell.textLabel.backgroundColor = \[UIColor clearColor\];
cell.detailTextLabel.backgroundColor = \[UIColor clearColor\];
cell.textLabel.textColor = \[UIColor colorWithRed:93.0f/255 green:94.0f/255 blue:94.0f/255 alpha:1.0\];
UIImageView *defaultImage = \[\[UIImageView alloc\]init\];
\[defaultImage setFrame:CGRectMake(5.0f, 5.0f, 40.0f, 40.0f)\];
\[cell addSubview:defaultImage\];
for (int i=0; i<\[self.exhibitorArray count\]; i++) {
NSString * string = \[\[self.exhibitorArray objectAtIndex:i\]valueForKey:#"name"\];
NSString *firstLetter = \[string substringToIndex:1\];
if (\[\[keys objectAtIndex:indexPath.section\] isEqualToString:firstLetter\] ) {
NSString *urlString = \[\[NSString alloc\]init\];
urlString = #"http://";
urlString = \[urlString stringByAppendingString:\[NSString stringWithFormat:#"%#",\[\[self.exhibitorArray objectAtIndex:i\]valueForKey:#"image"\]\]\];
NSLog(#"%#",urlString);
AsyncImageView *asyncImageView = \[\[AsyncImageView alloc\] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)\];
\[asyncImageView setBackgroundColor:\[UIColor clearColor\]\];
NSString *tmp_string = \[\[NSString alloc\]init\];
tmp_string = urlString;
\[asyncImageView loadImageFromURL:\[NSURL URLWithString:tmp_string\]\];
\[defaultImage addSubview:asyncImageView\];
defaultImage.contentMode = UIViewContentModeScaleAspectFit;
tmp_string = nil;
asyncImageView = nil;
defaultImage = nil;
NSString *name_string = \[\[NSString alloc\]init\];
name_string = \[\[self.exhibitorArray objectAtIndex:i\]valueForKey:#"name"\];
NSLog(#"%#",name_string);
UILabel *user_name = \[\[ UILabel alloc\]init \];
\[user_name setFrame:(CGRectMake(58, 5, 270, 25))\];
\[user_name setBackgroundColor: \[UIColor clearColor\]\];
\[user_name setText:name_string\];
\[user_name setFont:\[UIFont fontWithName:#"Roboto-Light" size:14\]\];
\[user_name setTextAlignment:NSTextAlignmentLeft\];
\[user_name setTextColor:\[UIColor colorWithRed:93.0f/255 green:94.0f/255 blue:94.0f/255 alpha:1.0\]\];
\[cell addSubview:user_name\];
user_name = nil;
}
}
\[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator\];
return cell;
}
They're not overlapping. You are adding an additional label each time the cell is used.
You need to only add one label to a cell and then reuse that label instead of adding a new one each time.
The same is true for the image views etc...
You're best solution is to use a custom UITableViewCell subclass... http://www.appcoda.com/customize-table-view-cells-for-uitableview/
Possible solution
Note: I don't like this because of the use of the tag property but it will get it done without subclassing UITableviewCell...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
UIImageView *defaultImageView;
UILabel *customLabel;
if (cell == nil) {
// create the cell and empty views ready to take the content.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
defaultImageView = //create the image view
defaultImageView.tag = 3;
[cell.contentView addSubview:defaultImageView];
customLabel = //create custom label
customLabel.tag = 4;
[cell.contentView addSubview:customLabel];
} else {
// get the views that have already been created
defaultImageView = [cell.contentView viewWithTag:3];
customLabel = [cell.contentView viewWithTag:4];
}
// now populate the views...
defaultImageView.image = someImage;
customLabel.text = #"Hello, world";
return cell;
}
This way you are only creating one label and one image view in the cell and then reusing it propelry.
Thats just because you are creating new labels on every cell datasource method just change
just alloc and add label in
if (cell == nil) {
cell = \[\[UITableViewCell alloc\] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier\];
**//Allocate label here and set tag**
UILabel *nameLabel = [[UILabel alloc] initwithframe];
[nameLabel setTag:212];
}
**get label here by tag and set text on it here.**
eg
UILabel *nameLabel = [cell viewWithTag:212];
Similarly add imageview inside condition and set images on that outside
Because of this line [cell addSubview:user_name]; It've added multiple times.To avoid this, try below:
UILabel *user_name = [[ UILabel alloc]init ];
user_name.tag = SomeTagValue;
.
.
.
.
UILabel *preView = [cell viewWithTag:SomeTagValue];
[preView removeFromSuperview];
[cell addSubview:user_name];
Change the line UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil]; with UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
Edit
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
UIView* bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
bgview.opaque = YES;
bgview.tag = 8888;
bgview.backgroundColor = [UIColor colorWithRed:244.0f/255 green:245.0f/255 blue:246.0f/255 alpha:1.0];
[cell setBackgroundView:bgview];
cell.textLabel.font = [UIFont fontWithName:#"Roboto-Light" size:17];
cell.detailTextLabel.font = [UIFont fontWithName:#"Roboto-Light" size:13];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor colorWithRed:93.0f/255 green:94.0f/255 blue:94.0f/255 alpha:1.0];
UIImageView *defaultImage = [[UIImageView alloc]init];
[defaultImage setFrame:CGRectMake(5.0f, 5.0f, 40.0f, 40.0f)];
defaultImage.contentMode = UIViewContentModeScaleAspectFit;
defaultImage.tag = 7777;
[cell.contentView addSubview:defaultImage];
UILabel *user_name = [[ UILabel alloc]init ];
user_name.tag = 9999;
[user_name setFrame:(CGRectMake(58, 5, 270, 25))];
[user_name setBackgroundColor: [UIColor clearColor]];
[user_name setFont:[UIFont fontWithName:#"Roboto-Light" size:14]];
[user_name setTextAlignment:NSTextAlignmentLeft];
[user_name setTextColor:[UIColor colorWithRed:93.0f/255 green:94.0f/255 blue:94.0f/255 alpha:1.0]];
[cell.contentView addSubview:user_name];
AsyncImageView *asyncImageView = [[AsyncImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
asyncImageView.tag = 6666;
[asyncImageView setBackgroundColor:[UIColor clearColor]];
[defaultImage addSubview:asyncImageView];
}
[self.exhibitorTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
UIImageView *defaultImage = (UIImageView*)[cell.contentView viewWithTag:7777];
UILabel *user_name = (UILabel*)[cell.contentView viewWithTag:9999];
AsyncImageView *asyncImageView = (AsyncImageView*)[defaultImage viewWithTag:6666];
for (int i=0; i<[self.exhibitorArray count]; i++) {
NSString * string = [[self.exhibitorArray objectAtIndex:i]valueForKey:#"name"];
NSString *firstLetter = [string substringToIndex:1];
if ([[keys objectAtIndex:indexPath.section] isEqualToString:firstLetter] ) {
NSString *urlString ;
urlString = #"http://";
urlString = [urlString stringByAppendingString:[NSString stringWithFormat:#"%#",[[self.exhibitorArray objectAtIndex:i]valueForKey:#"image"]]];
NSLog(#"%#",urlString);
NSString *tmp_string = urlString;
[asyncImageView loadImageFromURL:[NSURL URLWithString:tmp_string]];
NSString *name_string = [[self.exhibitorArray objectAtIndex:i]valueForKey:#"name"];
NSLog(#"%#",name_string);
[user_name setText:name_string];
}
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
You are adding both cell.TextLabel and another Label (Named: user_name). If you want a custom table cell with imageview and label you can see this.
As you can see in your output that label is overlapping. Its not the same label these are different labels in a cell. Hope this helps.. :)
Edit: Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = \[tableView dequeueReusableCellWithIdentifier:nil\];
if (cell == nil) {
cell = \[\[UITableViewCell alloc\] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier\];
}
\[self.exhibitorTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)\];
UIView* bgview = \[\[UIView alloc\] initWithFrame:CGRectMake(0, 0, 1, 1)\];
bgview.opaque = YES;
bgview.backgroundColor = \[UIColor colorWithRed:244.0f/255 green:245.0f/255 blue:246.0f/255 alpha:1.0\];
\[cell setBackgroundView:bgview\];
UIImageView *defaultImage = \[\[UIImageView alloc\]init\];
\[defaultImage setFrame:CGRectMake(5.0f, 5.0f, 40.0f, 40.0f)\];
\[cell addSubview:defaultImage\];
for (int i=0; i<\[self.exhibitorArray count\]; i++) {
NSString * string = \[\[self.exhibitorArray objectAtIndex:i\]valueForKey:#"name"\];
NSString *firstLetter = \[string substringToIndex:1\];
if (\[\[keys objectAtIndex:indexPath.section\] isEqualToString:firstLetter\] ) {
NSString *urlString = \[\[NSString alloc\]init\];
urlString = #"http://";
urlString = \[urlString stringByAppendingString:\[NSString stringWithFormat:#"%#",\[\[self.exhibitorArray objectAtIndex:i\]valueForKey:#"image"\]\]\];
NSLog(#"%#",urlString);
AsyncImageView *asyncImageView = \[\[AsyncImageView alloc\] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)\];
\[asyncImageView setBackgroundColor:\[UIColor clearColor\]\];
NSString *tmp_string = \[\[NSString alloc\]init\];
tmp_string = urlString;
\[asyncImageView loadImageFromURL:\[NSURL URLWithString:tmp_string\]\];
\[defaultImage addSubview:asyncImageView\];
defaultImage.contentMode = UIViewContentModeScaleAspectFit;
tmp_string = nil;
asyncImageView = nil;
defaultImage = nil;
NSString *name_string = \[\[NSString alloc\]init\];
name_string = \[\[self.exhibitorArray objectAtIndex:i\]valueForKey:#"name"\];
NSLog(#"%#",name_string);
UILabel *user_name = \[\[ UILabel alloc\]init \];
\[user_name setFrame:(CGRectMake(58, 5, 270, 25))\];
\[user_name setBackgroundColor: \[UIColor clearColor\]\];
\[user_name setText:name_string\];
\[user_name setFont:\[UIFont fontWithName:#"Roboto-Light" size:14\]\];
\[user_name setTextAlignment:NSTextAlignmentLeft\];
\[user_name setTextColor:\[UIColor colorWithRed:93.0f/255 green:94.0f/255 blue:94.0f/255 alpha:1.0\]\];
\[cell addSubview:user_name\];
user_name = nil;
}
}
\[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator\];
return cell;
}
i've implemented, in my iOS ap, some TdBadgedCell (from https://github.com/tmdvs/TDBadgedCell) in a UITabView. But when I want to manage the cells' hight dynamically by using something like this example:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
the cell's width is the entire width of the cell (calculated variable "constraint" in the example below) and not the real width of the label printed on screen taking consideration of the badge's width. So, the portion of text at the end of the UILabel doesn't appear in cell when the text in too long.
How can I resolve this please?
I've solved my own problem with this portions of code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
MyObject *obj = [self.myObjects objectAtIndex:indexPath.row];
NSString *textlabel = [self getMainTextStringFromMyObject:obj];
NSString *detailtextlabel = [self getDetailTextStringFromMyObject:obj];
CGFloat height = MAX(CELL_TEXTLABEL_HEIGHT + [self getDetailTextSizeForString:detailtextlabel].height, CELL_ROW_DEFAULTHEIGHT);
return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyObject *obj = [self.myObjects objectAtIndex:indexPath.row];
NSString *textlabel = [self getMainTextStringFromMyObject:obj];
NSString *detailtextlabel = [self getDetailTextStringFromMyObject:obj];
static NSString *CellIdentifier = #"ImageOnRightCell";
UILabel *mainLabel, *secondLabel;
UIImageView *photo;
TDBadgedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CELL_LABELS_MARGIN, 1.0, CELL_TEXTLABEL_WIDTH, CELL_TEXTLABEL_HEIGHT)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont boldSystemFontOfSize:CELL_TEXTLABEL_FONTSIZE];
mainLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CELL_LABELS_MARGIN, CELL_TEXTLABEL_HEIGHT, CELL_TEXTLABEL_WIDTH, 19.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont systemFontOfSize:CELL_DETAILTEXTLABEL_FONTSIZE];
secondLabel.textColor = [UIColor darkGrayColor];
secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
secondLabel.numberOfLines = 0;
secondLabel.lineBreakMode = UILineBreakModeWordWrap;
[cell.contentView addSubview:secondLabel];
float yOriginImg = (cell.contentView.frame.size.height/2.0);
if((CELL_TEXTLABEL_HEIGHT + [self getDetailTextSizeForString:detailtextlabel].height) <= CELL_ROW_DEFAULTHEIGHT)
{
yOriginImg -= (CELL_IMGHEIGHT/2.0);
}
photo = [[[UIImageView alloc] initWithFrame:CGRectMake(CELL_LABELS_MARGIN+CELL_TEXTLABEL_WIDTH, yOriginImg, CELL_IMGWIDTH, CELL_IMGHEIGHT)] autorelease];
photo.tag = PHOTO_TAG;
[cell.contentView addSubview:photo];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];
}
mainLabel.text = textlabel;
secondLabel.text = detailtextlabel;
cell.badgeString = [NSString stringWithFormat:#"%g",obj.duration];
UIImage *theImage = [UIImage imageNamed:#"right_cell_icon.png"];
photo.image = theImage;
return cell;
}
- (NSString*) getMainTextStringFromMyObject:(MyObject*) obj
{
return obj != nil? obj.name : nil;
}
- (NSString*) getDetailTextStringFromMyObject:(MyObject*) obj
{
return obj.detail != nil ? obj.detail : nil;
}
- (CGSize) getDetailTextSizeForString:(NSString*) str
{
CGSize constraint = CGSizeMake(CELL_TEXTLABEL_WIDTH - (CELL_LABELS_MARGIN * 2), 20000.0f);
return [str sizeWithFont:[UIFont systemFontOfSize:CELL_DETAILTEXTLABEL_FONTSIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
}