I have a tableView with custom cells. One of the objects in the cell is a textField.
The tableViewController is the textFieldDelegate.
The datasource for the table is an array of objects.
When the user tap on the textField, the tableViewController implements textField delegates methods controlling this way the data entry.
To use the data entered by user, the tableViewController implements the following:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
CGPoint point = [textField center];
point = [self.tableView convertPoint:point fromView:textField];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
...
...
return YES
}
I spent two hours trying to figure out why indexPath.row was always wrong, it was always row+1 of what it suppose to be.
Solution: In the storyboard I move the textField to the upper portion of the cell.
Has anyone see something like this before?
Thanks.
-[UIView center] returns the center of the view's frame, which is in the view's superview's coordinate system. But -[UIView convertPoint:fromView:] expects to be given a point in the "from" view's coordinate system.
Either give it the same point, and tell it to convert from the correct view:
CGPoint point = [textField center];
point = [self.tableView convertPoint:point fromView:textField.superview];
Or give it a point in the view's coordinate system, and tell it to convert from the view:
CGRect textFieldBounds = textField.bounds;
CGPoint point = CGPointMake(CGRectGetMidX(textFieldBounds), CGRectGetMidY(textFieldBounds));
point = [self.tableView convertPoint:point fromView:textField];
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [array_loaddata objectAtIndex:indexPath.row] ;
UIFont *font = [UIFont systemFontOfSize:10];
CGSize size = [(text ? text : #"") sizeWithFont:font constrainedToSize:CGSizeMake(220, 9999) lineBreakMode:NSLineBreakByWordWrapping];
int count = size.height + 0;
return count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array_loaddata count];
}
- (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];
CGSize size = [(text ? text : #"") sizeWithFont:font constrainedToSize:CGSizeMake(220, 9999) lineBreakMode:NSLineBreakByWordWrapping];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(46, 0, size.width, 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];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
link==http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api/
/*
NSString *appurl =[NSString stringWithFormat:#"xx"];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
*/
}
Related
I have a label in a TableViewCell in which there are more than one lines of text. Initially on the label it shows only one line. I have a button on that cell. I want to expand the cell by clicking on the button upto the hight of the label's text.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"tabCell";
_cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.persons objectAtIndex:indexPath.row];
UILabel *nameLabel = (UILabel*)[_cell.contentView viewWithTag:2];
nameLabel.text = [NSString stringWithFormat:#"%#", [device valueForKey:#"name"]];
UILabel *dateLabel = (UILabel *)[_cell.contentView viewWithTag:3];
dateLabel.text = [NSString stringWithFormat:#"%#",[device valueForKey:#"date"]];
UILabel *descLabel = (UILabel *)[_cell.contentView viewWithTag:4];
//descTextView.text = [NSString stringWithFormat:#"%#",[device valueForKey:#"desc"]];
UIImageView *personImage = (UIImageView *)[_cell.contentView viewWithTag:1];
UIImage *personImg = [UIImage imageWithData:[device valueForKey:#"image"]];
personImage.image = personImg;
UIButton *viewMoreButton = (UIButton *)[_cell.contentView viewWithTag:5];
[viewMoreButton addTarget:self
action:#selector(myAction)
forControlEvents:UIControlEventTouchUpInside];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:[device valueForKey:#"desc"]
attributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:17]}];
reqFrame=[attrString boundingRectWithSize:CGSizeMake(descLabel.frame.size.height, CGFLOAT_MAX)options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
descLabel.attributedText = attrString;
return _cell;
}
- (void)myAction{
//what to write here?
}
First of all it is not a good practice to build cell in cellForRowAtIndexPath. Use willDisplayCell instead. See here why.
Secondly to do what you want you have to set desired height in heightForRowAtIndexPath. Once this accomplished, within your button selector call to refresh specific cells using
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
The implementation is similar:
- (void)buttonSelector
{
myLabel.text = #"YOUR TEXT";
[myLabel sizeToFit];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
...
return yourLabel.height;
}
Anyhow need to get reference of the cell and indexPath on which the button is tapped in your myAction().
Create a private variable CGFloat newCellHeight; and initialize it to 0.0.
Let reference to the associated cell is selectedCell and selected index path is indexPathOfTappedCell.
- (void)myAction{
UILabel *descLabel = (UILabel*)[selectedCell.contentView viewWithTag:4];
[descLabel sizeToFit]; // Automatically increases the height of the label as required
newCellHeight = CGRectGetMaxY(descLabel.frame) + 10.0; // Extra padding 10.0
[tableView reloadRowsAtIndexPaths:#[indexPathOfTappedCell] withRowAnimation:UITableViewRowAnimationAutomatic];
}
Now add the following TableView delegate method in your view controller
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == indexPathOfTappedCell.section &&
indexPath.row == indexPathOfTappedCell.row ) {
return newCellHeight;
}
return 44.0; // Suppose default height is 44.0
}
you need to maintain two variables, just give tag to your button, and detect in action by its tag to reload that particular cell and another BOOL variable to detect if button touched. You should calculate height in heightForRowAtIndexPath method. I am posting code, it may help you
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if(isReadMoreButtonTouched && [indexPath row]== indexOfReadMoreButton) {
NSString *yourText = [arr1 objectAtIndex:indexPath.row]; // your text
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Avenir Next" size:14], NSFontAttributeName,
[UIColor grayColor], NSForegroundColorAttributeName,
nil]; // set custom attributes
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:yourText attributes:attributes];
CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(625, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil]; //here 625 is width of label
NSLog(#"height = %f", paragraphRect.size.height);
return paragraphRect.size.height;
}
else{
return 200; //default height taken in storyboard
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
cell.lblKB.text = [arr objectAtIndex:indexPath.row];
cell.lblDetail.text = [arr1 objectAtIndex:indexPath.row];
NSString *yourText = [arr1 objectAtIndex:indexPath.row];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Avenir Next" size:14], NSFontAttributeName,
GrayColor, NSForegroundColorAttributeName,
nil]; //your custom attributes
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:yourText attributes:attributes];
CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(625, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
NSLog(#"height = %f", paragraphRect.size.height);
if (paragraphRect.size.height<200) {
cell.btnMore.hidden = YES;
}
else{
cell.btnMore.hidden = NO;
}
cell.btnMore.tag = indexPath.row;
return cell;
}
// action of button click
-(IBAction)MoreBtnClicked:(id)sender {
if (!isReadMoreButtonTouched) {
isReadMoreButtonTouched = YES;
}
else{
isReadMoreButtonTouched = NO;
}
indexOfReadMoreButton = [sender tag];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:0];
[self.tblKB reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; //reload that cell of your tableview
}
I have UITableViewCell and inside that I have UITextfield, I made 7 sections (dynamic) and each section have one cell (one row) which includes UITextField .
Now I have one button on right top corner of UINavigationBar (EDIT button).
I need to enable user interaction enable for all section textfields . Hows that possible?
This is my UITableviewCode
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
sharedManager=[Mymanager sharedManager];
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//UITableViewCell *cell;
UILabel *label = nil;
NSString *text;
cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil)
{
cell = [[timeLineDetailsCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"cell"];
label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setMinimumFontSize:FONT_SIZE];
[label setNumberOfLines:0];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label setTag:1];
[[label layer] setBorderWidth:2.0f];
[[cell contentView] addSubview:label];
}
if(indexPath.section==0){
text = [contents objectAtIndex:0];
}else if(indexPath.section==1){
text = [contents objectAtIndex:1];
}else if(indexPath.section==2){
text = [contents objectAtIndex:2];
}else if(indexPath.section==3){
text = [contents objectAtIndex:3];
}else if(indexPath.section==4){
text = [contents objectAtIndex:4];
}else if(indexPath.section==5){
text = [contents objectAtIndex:5];
}else if(indexPath.section==6){
text = [contents objectAtIndex:6];
}else if(indexPath.section==7){
text = [contents objectAtIndex:7];
}
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
if (!label)
label = (UILabel*)[cell viewWithTag:1];
[cell.ds1 setText:text];
[cell.ds1 setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text ;
if(indexPath.section==0){
text = [contents objectAtIndex:0];
}else if(indexPath.section==1){
text = [contents objectAtIndex:1];
}else if(indexPath.section==2){
text = [contents objectAtIndex:2];
}else if(indexPath.section==3){
text = [contents objectAtIndex:3];
}else if(indexPath.section==4){
text = [contents objectAtIndex:4];
}else if(indexPath.section==5){
text = [contents objectAtIndex:5];
}else if(indexPath.section==6){
text = [contents objectAtIndex:6];
}else if(indexPath.section==7){
text = [contents objectAtIndex:7];
}
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);
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *str= [title objectAtIndex:section];
return str;
}
my edit button code is
-(void)editTimeline{
cell.ds1.userInteractionEnabled=YES;
[cell.ds1 setUserInteractionEnabled:TRUE];
cell.ds1.layer.borderColor=[UIColor lightGrayColor].CGColor;
cell.ds1.layer.borderWidth=1;
// [cell.ds1 becomeFirstResponder];
}
when i click on EDIT button only some rows are able to edit .please help me .
define flag data memeber with Bool type
-(void)editTimeline{
flag=true;
[self.tableView reload];
}
add following condition in cellForRowAtIndexpath method
if(flag==true){
[cell.ds1 setUserInteractionEnabled:TRUE];
}
else{
[cell.ds1 setUserInteractionEnabled:NO];
}
let me know if it help u....!!!
I would use this code -
NSArray *cellArray=[itemsTable visibleCells];
for (UITableViewCell *aCell in cellArray)
{
UITextField *myTField=(UITextField*)yourtextField;
myTField.userInteractionEnabled=YES;
}
myTField is added on cell as a subView with specific tag. You can get the myTField via [aCell viewWithTag:someTag];.
Call cellForRowAtIndexPath for each row in your section, make it unselectable by the tableView (otherwise it will triger the tap instead of you) and enable user interactions in the way you want for you returned cell :3
I'm creating a messenger app, which displays a dialog between two people.
Parsing API response, I got text for inbox and outbox messages. Then I create a cell, using a UITableViewCell prototype from the storyboard.
All constraints are adjusted correctly.
The problem is that I use
[self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
to scroll the tableView to the bottom to have the last message in focus but the contentView of the upper cells is not counted at this time.
So i had to count height of cell before it is displayed. For this i use
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
RJMessageCell *cell = [self configureBasicCellAtIndexPath:indexPath];
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGSize maximumSize = CGSizeMake(320.0, UILayoutFittingCompressedSize.height);
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:maximumSize].height;
return height;
}
- (RJMessageCell *)configureBasicCellAtIndexPath:(NSIndexPath *)indexPath {
static NSString *inboxIdentifier = #"Inbox";
static NSString *outboxIdentifier = #"Outbox";
NSString *identifier;
RJMessage *message = [[[self.messageSectionsArray objectAtIndex:indexPath.section] messages] objectAtIndex:indexPath.row];
if (message.messageIsMine) {
identifier = outboxIdentifier;
} else {
identifier = inboxIdentifier;
}
RJMessageCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];
cell.messageView.layer.cornerRadius = 10.f;
cell.messageView.clipsToBounds = YES;
if ([message.text isEqualToString:#""]) {
cell.messageTextLabel.text = #" ";
} else {
cell.messageTextLabel.text = message.text;
}
cell.messageTextLabel.numberOfLines = 0;
cell.messageTextLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.timeLabel.text = [self stringTimeFromTimeInterval:message.messageInterval];
if (message.messageState == RJMessageStateUnread) {
cell.backgroundColor = [UIColor colorWithRed:151/255.0 green:200/255.0 blue:255/255.0 alpha:0.4];
} else {
cell.backgroundColor = [UIColor clearColor];
}
return cell;
}
Also the UILabel on screenshots are custom, to setBounds to label
- (void)setBounds:(CGRect)bounds {
[super setBounds:bounds];
if (self.numberOfLines == 0 && bounds.size.width != self.preferredMaxLayoutWidth) {
self.preferredMaxLayoutWidth = self.bounds.size.width;
[self setNeedsUpdateConstraints];
}
}
And the last thing i do, adding estimatedRowHeight in viewDidLoad
self.tableView.estimatedRowHeight = self.tableView.rowHeight;
self.tableView.rowHeight = UITableViewAutomaticDimension;
The first time they appear everything looks good, but when I scroll the table up and down, my cells change their size randomly.
What's wrong with the cell height?
You have to return Height by calculating the text width & height which you want to place inside the cell.
//Height For Row at index path
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = [NSString stringWithFormat:#"%#",[arrDataSource[indexPath.row]]];
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:15.0];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width - 90.0, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return rect.size.height + 42;
}
I found a lot of answer for this question but I don't anderstand how to manage my code.
When I scroll the tableView content, the cell disappear. I just have two texts in the cell question and answer.
I've tried to use an identifier (reusable) but the code doesn't change anything...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *textLabel = nil;
NSString* text = #"";
//static NSString *CellIdentifier = #"Cell";
NSString *CellIdentifier = [NSString stringWithFormat:#"%ld_%ld",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
int y = -20;
float titleFontSize = 14.0f;
if(indexPath.row == 0) {
y = 0;
titleFontSize = 16.0f;
}
if(cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[textLabel setLineBreakMode:NSLineBreakByWordWrapping];
[textLabel setMinimumFontSize:14.0f];
[textLabel setNumberOfLines:0];
[textLabel setFont:[UIFont systemFontOfSize:14.0f]];
[textLabel setTag:1];
[textLabel setTextColor:[UIColor colorWithRed:57/255.0 green:55/255.0 blue:64/255.0 alpha:1.0]];
// Titre
if(indexPath.row == 0) {
text = question;
[cell setBackgroundColor:[UIColor colorWithRed:220/255.0 green:224/255.0 blue:241/255.0 alpha:1.0]];//[UIColor colorWithRed:.945f green:.921f blue:.78f alpha:1]];
[textLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:titleFontSize]];
}
// Contenu
else {
text = answer;
}
CGSize constraint = CGSizeMake(285, 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:titleFontSize] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
[textLabel setText:text];
[textLabel setFrame:CGRectMake(25, y, 275, MAX(size.height + 60, 44.0f))];
[textLabel setBackgroundColor:[UIColor clearColor]];
[cell addSubview:textLabel];
return cell;
}
UPDATE CALCULATING CELL SIZE
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
float titleFontSize = 14.0f;
float offSet = 0;
NSString *text = #"";
if(indexPath.row == 0) {
text = question;
titleFontSize = 16.f;
offSet = 10;
}
else
text = answer;
CGSize constraint = CGSizeMake(285, 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:titleFontSize] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height + 40, 44.0f);
return height + offSet;
}
I've had this problem in the past and it's always due to the cells height being incorrect... You've got quite a few instances where your two cells are not the same, so we are going to have to get a grip on that code.
int y
this value is also concerning me a little as it looks like it sets the textLabel frame origin.y to -20 ... if you want a different offset for Y in each cell but the rest of the cell is the same, that's fine, but in this case I think I'd suggest a different UITableViewCell subclass for the two types of cell... And change all the label properties etc inside that subclass..
So...
Make a UITableViewCell subclass for each type of cell, call them whatever you like... for example MYQuestionTableViewCell and MYAnswerTableViewCell
inside the cell MYQuestionTableViewCell .h file
#define TEXT_LABEL_WIDTH 285.0f
#define TEXT_LABEL_QUESTION_FONT_SIZE 16.0f
inside that cell MYQuestionTableViewCell .m file do
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.backgroundColor = [UIColor redColor];
self.clipsToBounds = YES; // just to make sure we're calculating the height correctly
// set up your textLabel etc. in here
self.textLabel.textColor = [UIColor whiteColor];
self.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: TEXT_LABEL_QUESTION_FONT_SIZE]];
}
return self;
}
-(void)layoutSubviews
{
[super layoutSubviews];
self.textLabel.frame = CGRectMake(0.0f, 0.0f, TEXT_LABEL_WIDTH, self.contentView.frame.size.height);
}
Now our textLabel will be whatever the height of the cell is... Now it's set in only one place, we know where the issue will be if it's not correct.
In your second MYAnswerTableViewCell subclass you'll need the other values set
.h
#define TEXT_LABEL_ANSWER_FONT_SIZE 14.0f
.m
same as the other cell but changing for it's property values
As you are also using different fonts in the two different cells... it might be easier to use a switch.. but I'll try to keep it similar to what you were doing before.. this sort of doubling up of code is the cause of the confusion, but sometimes it's unavoidable.. We'll just try to keep it as simple as we can.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat offSet = 0.0;
NSString *text = #"";
UIFont *fontUsed = nil;
if(indexPath.row == 0) {
fontUsed = [textLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size: TEXT_LABEL_QUESTION_FONT_SIZE]];
text = question;
offSet = 10.0f;
}
else
{
fontUsed =[UIFont systemFontOfSize:TEXT_LABEL_ANSWER_FONT_SIZE];
text = answer;
}
NSLog (#"TEXT: %#",text); // checking if the text is set...
CGSize constraint = CGSizeMake(TEXT_LABEL_WIDTH, HUGE_VALF); // personally I prefer HUGE_VALF for that
CGSize size = [text sizeWithFont:fontUsed constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height + 40.0f, 44.0f); // 40.0f for padding?
return height + offSet;
}
You shouldn't be adding labels to a cell unless you need to, they come with some provided... now your cellForRow can look like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *QuestionCellIdentifier = #"QuestionCell";
static NSString *AnswerCellIdentifier = #"AnswerCell";
if (indexPath.row == 0)
{
MYQuestionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:QuestionCellIdentifier];
if (!cell)
cell = [[MYQuestionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:QuestionCellIdentifier];
cell.textLabel.text = question;
return cell;
}
MYAnswerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: AnswerCellIdentifier];
if (!cell)
cell = [[MYAnswerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AnswerCellIdentifier];
cell.textLabel.text = answer;
return cell;
}
You'll also need
#import "MYQuestionTableViewCell.h"
#import "MYAnswerTableViewCell.h"
at the top of your view controller
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;
}