UITextView doesn't display in multiple lines - ios

I have a UITableViewCell that has a UITextView. When the table loads all of the text in each UITextView appears in a single line. I created the UITextView in IB with a white text color. How do I get it to display in multiple lines, and why did the text color switch to black?
The height of each UITableViewCell is correct. It used to display the text in multiple lines after I refreshed the table by pulling down, but for some reason that stopped working too.
If there's any other information you require, please let me know.
Here's the relevant code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
BIDChatCell *cell = (BIDChatCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[BIDChatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell
cell.backgroundColor = [UIColor clearColor];
cell.userLabel.text = [object objectForKey:#"username"];
NSString *time = [object objectForKey:#"time"];
NSString *date = [time substringToIndex:10];
cell.timeLabel.text = date;
NSString *chatText = [object objectForKey:#"text"];
UIFont *font = [UIFont systemFontOfSize:14];
CGSize size = [chatText sizeWithFont:font constrainedToSize:CGSizeMake(200.0f, 1000.0f) lineBreakMode:UILineBreakModeCharacterWrap];
cell.textStringView.frame = CGRectMake(75, 15, size.width +20, size.height + 20);
cell.textStringView.font = [UIFont fontWithName:#"Helvetica" size:14.0];
cell.textStringView.text = chatText;
[cell.textStringView sizeToFit];
[cell.textStringView.textContainer setSize:cell.textStringView.frame.size];
CGRect frame = cell.textStringView.frame;
frame.size.height = cell.textStringView.contentSize.height;
cell.textStringView.frame = frame;
[cell layoutSubviews];
return cell;
}
Here's an image:

Try setting the height of the textView like so:
CGRect frame = cell.textStringView.frame;
frame.size.height = cell.textStringView.contentSize.height;
cell.textStringView.frame = frame;

Does the UITextView have the proper autoresizingMask?
It likely needs it set to (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight) to allow the textview to grow (as it normally uses a UIScrollView instead)

Related

TableView cell disappear on scroll

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

UITableView cell contents not displayed properly

I use auto layout and want to display UITableView with custom cell that has a UITextView with variable content.
Cells are displayed as shown below. For chat message, when cell is first displayed only 2-3 characters are displayed in a single line and next characters are forced to go to next line. But when I scroll tableView so that these cells are not visible and scroll back to make them visible (I do this so that when they are visible again cellForRowAtIndexPath: method is called again to render the cell), they render the cell properly as shown in second image.
Code :
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [chatData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
RS_User *user = [[RS_User alloc]init];
chatCell *cell = (chatCell *)[tableView dequeueReusableCellWithIdentifier:CHAT_CELL_IDENTIFIER];
NSUInteger row = indexPath.row;
cell.chatCellBackground.image = nil;
NSString *chatText = [[chatData objectAtIndex:row] objectForKey:TEXT]; // get text string(message) from array
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
UIFont *font = [UIFont systemFontOfSize:FONT_SIZE];
cell.textString.font = [UIFont fontWithName:FONT_NAME size:FONT_SIZE]; // set text font
cell.textString.text = chatText;
// set text
CGSize size = [cell.textString.text sizeWithFont:cell.textString.font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
cell.textString.frame = ...;
[cell.textString sizeToFit];
NSDate *theDate = [[chatData objectAtIndex:row] objectForKey:DATE];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:DATE_FORMAT];
NSString *timeString = [formatter stringFromDate:theDate];
cell.timeLabel.text = timeString; // set timeLabel to display date and time
cell.timeLabel.font = [UIFont fontWithName:FONT_NAME size:SMALL_FONT_SIZE];
cell.userLabel.text = #"Name";//[[chatData objectAtIndex:row] objectForKey:NAME]; // set userLabel to display userName
CGSize size1 = [cell.userLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
// check cell contains sender name or receiver name
if (thisCellIsForSender)
{
// Set bubble for sender
cell.chatCellBackground.image = [[UIImage imageNamed:#"bubbleMine.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
cell.chatCellBackground.frame = ...;
}
else
{
// set bubble for receiver
cell.chatCellBackground.image = [[UIImage imageNamed:#"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
cell.chatCellBackground.frame = ...;
}
[cell setNeedsLayout];
[cell layoutIfNeeded];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
RS_User *user = [[RS_User alloc]init];
chatCell *cell = (chatCell *)[tableView dequeueReusableCellWithIdentifier:CHAT_CELL_IDENTIFIER];
NSUInteger row = indexPath.row;
cell.chatCellBackground.image = nil;
NSString *chatText = [[chatData objectAtIndex:row] objectForKey:TEXT]; // get text string(message) from array
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
UIFont *font = [UIFont systemFontOfSize:FONT_SIZE];
cell.textString.font = [UIFont fontWithName:FONT_NAME size:FONT_SIZE]; // set text font
cell.textString.text = chatText;
// set text
CGSize size = [cell.textString.text sizeWithFont:cell.textString.font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
cell.textString.frame = ...;
[cell.textString sizeToFit];
NSDate *theDate = [[chatData objectAtIndex:row] objectForKey:DATE];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:DATE_FORMAT];
NSString *timeString = [formatter stringFromDate:theDate];
cell.timeLabel.text = timeString; // set timeLabel to display date and time
cell.timeLabel.font = [UIFont fontWithName:FONT_NAME size:SMALL_FONT_SIZE];
cell.userLabel.text = [[chatData objectAtIndex:row] objectForKey:NAME]; // set userLabel to display userName
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
CGSize size1 = [cell.userLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
// check cell contains sender name or receiver name
if (thisCellIsForSender)
{
// Set bubble for sender
cell.chatCellBackground.image = [[UIImage imageNamed:#"bubbleMine.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
cell.chatCellBackground.frame = ...;
}
else
{
// set bubble for receiver
cell.chatCellBackground.image = [[UIImage imageNamed:#"bubbleSomeone.png"] stretchableImageWithLeftCapWidth:STRETCHED_WIDTH topCapHeight:STRETCHED_HEIGHT];
cell.chatCellBackground.frame = ...;
}
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];
return cell.bounds.size.height;
}
UPDATE : I could solve some of the issues from coverback's answer. Still cell is not laid out correctly. I am adding photos for constraints of each UI object in cell.
User name :
Time stamp :
Chat message :
Bubble image :
Cell Layout :
Cell height in cellForRowAtIndexPath: is always 100 even though I return different value from heightForRowAtIndexPath: method. Cell height in storyboard is 100.
Chat message in third cell is clipped from bottom.
Time stamps and chat message labels are some time not aligned properly to each other even though both have constraint vertical spacing from username label.
Username label in third cell is vanished.
Do you see anything wrong in constraints? You can ask me if analyzing constraints is difficult.
Combining the answers by thandasoru and coverback solved my issue. Below is the code I use.
I added below method in custom UITableViewCell's class.
- (void)layoutSubviews
{
[super layoutSubviews];
CGFloat maxTextWidth = [UIScreen mainScreen].bounds.size.width * 0.40;
self.userLabel.preferredMaxLayoutWidth = maxTextWidth;
self.chatMessage.preferredMaxLayoutWidth = maxTextWidth;
self.timeLabel.preferredMaxLayoutWidth = self.timeLabel.frame.size.width;
[super layoutSubviews];
}
UITableView datasource methods :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell * cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"customCellId"];
// Set all label's text and image to ImageView
...
// Update layout
[cell setNeedsLayout];
[cell layoutIfNeeded];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCell * cell = (customCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
NSString * userName = cell.userLabel.text;
NSString * chatText = cell.chatMessage.text;
// Get bounding rect of userName label
CGRect userNameFrame = [userName boundingRectWithSize:CGSizeMake(maxLabelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:cell.userLabel.font} context:nil];
// Get bounding rect of chatMessage label
CGRect chatTextFrame = [chatText boundingRectWithSize:CGSizeMake(maxLabelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:cell.chatMessage.font} context:nil];
// Calculate cell height from its contents
height = userNameFrame.size.height + chatTextFrame.size.height + PADDING_ABOVE_TOP_LABEL + DISTANCE_BETWEEN_TWO_LABELS + PADDING_BELOW_BOTTOM_LABEL;
return height;
You can determine the cell height dynamically so that the text appears on one line. I've given CGSize(320,568) as bounds. But you can change the size as you see fit
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *chatText = [[chatData objectAtIndex:row] objectForKey:TEXT];
CGRect frame = [chatText boundingRectWithSize:CGSizeMake(320,568) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:18.0f]} context:nil];
return frame.height; //returns cell's height after calculating the area that text needs
}
You are setting the frame of the text and calling sizeToFit:
CGSize size = [cell.textString.text sizeWithFont:cell.textString.font constrainedToSize:CGSizeMake(SET_WIDTH, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
cell.textString.frame = ...;
[cell.textString sizeToFit];
This will not be working with autolayout. You need to remove setting the frame and sizeToFit completely, same goes for all other frame being set directly. If things don't work after that, it would mean some constraints are not correct. But mixing approaches always breaks layout.
For UILabels, make sure to also set preferredMaxLayoutWidth to label's width, otherwise text may not wrap correctly:
- (void)layoutSubviews
{
[super layoutSubviews];
self.label.preferredMaxLayoutWidth = self.label.frame.size.width;
[super layoutSubviews];
}
Also, your height calculating method should not just do same thing as cellForRowAtIndexPath:, if you want to use the same code, just call that other method to get a cell.

Setting UITableViewCell height and the cell's text label based on the text height

I have followed the instructions I have been able to find on stackoverflow to fix the following but none have worked. Below is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"DoCCell";
DoCCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[DoCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
CGSize constraintSize = CGSizeMake(cell.infoLabel.frame.size.width, MAXFLOAT);
CGSize labelSize = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:12.0f]
constrainedToSize:constraintSize
lineBreakMode:NSLineBreakByWordWrapping];
CGRect frame = CGRectMake (cell.infoLabel.frame.origin.x, cell.infoLabel.frame.origin.y, labelSize.width, labelSize.height);
[cell.infoLabel setFrame:frame];
cell.infoLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.infoLabel.numberOfLines = 10;
_font = cell.infoLabel.font;
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize size = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:12.0f]
constrainedToSize:constraintSize
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 30.0;
}
but when I run my code the height of the cells is changed appropriately while the label size is not.
The cell is a custom cell and I have added the label via the .xib file. I tried manually stretching the label which worked in the sense that it would display all of the text so the issue is not in the wrapping of the label. I have also tested the cell.infoLabel.frame.size.height and the height value DOES change with the height of the cell as far as the value is concerned but it is not displayed as such. What am I doing wrong?
I think that the problem might be of adjusting the vertical alignment of the text in the UILabel instance.
I think you should do the following inside cellForRowAtIndexPath:
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.infoLabel.numberOfLines = 0;
[cell.infoLabel sizeToFit];
More details about it can be found in the following link: Vertical Alignment of UILabel Text
Hope this helps! :)
Use below code in cellForRowAtIndexPath delegate of tableView :
// getDynamicHeight function calculates height based on text length
//Dynamically determine height for cell text
CGFloat calculatedHeight = [self getDynamicHeight:#"Some very long text here"];
//Set name label frame based on text height
cell.infoLabel.frame = CGRectMake(cell.infoLabel.frame.origin.x,cell.infoLabel.frame.origin.y, cell.infoLabel.frame.size.width,calculatedHeight);
cell.infoLabel.numberOfLines = 5;
cell.infoLabel.text = #"Some very long text here";
// getDynamicHeight function
//Dynamically determine height for cell based in containing Text
-(CGFloat) getDynamicHeight : (NSString *) strCellTextName {
UILabel *lblGetDynamicHeight = [[UILabel alloc] init];
lblGetDynamicHeight.lineBreakMode = UILineBreakModeWordWrap;
lblGetDynamicHeight.text = strCellTextName;
CGSize labelStringSize = [lblGetDynamicHeight.text sizeWithFont:lblGetDynamicHeight.font constrainedToSize:CGSizeMake(142, 9999) lineBreakMode:lblGetDynamicHeight.lineBreakMode];
return labelStringSize.height; }

ios - list items have text cut off after a certain length

I have a list view that sometimes has long text. When the text is a few paragraphs, it tends to get cut off at some point. Part of the strange behavior is that it does not always get cut off at the same character, but kind of random.
Here is the code that I use to populate the list:
// CREATING EACH CELL IN THE LIST
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//static const NSInteger kLabelTag = 1;
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault)
reuseIdentifier:#"business"];
NSString *comment = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"comment")];
NSString *first_name = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"first_name")];
//Boolean *is_private = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"is_private")];
// Creating a constraint size for the label you are making
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
// Determining the size that you will need for the label based on the comment
// length and the contraint size
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
// Creating the label and initializing it with the frame that you have
// determined by your size calculations above
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, MAX(size.height, 44.0f) + 20.0f)];
// setting up the label properties
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *is_private = [standardUserDefaults objectForKey:#"is_private"];
if ( is_private == nil )
{
label.text = [first_name stringByAppendingString:[#": " stringByAppendingString:comment]]; // comment;
}
else
if ( [is_private isEqualToString:#"0"])
{
label.text = [first_name stringByAppendingString:[#": " stringByAppendingString:comment]]; // comment;
}
else
{
label.text = comment;
}
// adding the label view to the cell that you have created
[cell.contentView addSubview:label];
// CLOSE THE SPINNER
[spinner stopAnimating];
// return the cell for the table view
return cell;
}
//This method will determine how tall each row needs to be. Cell size for word wrapping.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *comment = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"comment")];
// Again you are getting the constraints because you are going to us this size
// to constrain the height of the cell just like you determined the size for the label.
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
// Again, determining the size that we will need for the label, because it will drive
// the height of the cell
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
// Finally, we can determine the height for the cell!
CGFloat height = MAX(size.height, 44.0f);
// return the height, which is the height of the label plus some extra space to make
// it look good.
return height + (10 * 2);
}
Does this code have anything particularly incorrect with it? Or is the problem possibly rooted elsewhere?
Thanks!
when you create the label, you hand it a max height
MAX(size.height, 44.0f)
which means the label is never higher than 44 points.
If the text (which is being wrapped to fit the width of the label) is higher than the label, the lines that fallow below it will still be in the label, but not visible.
Your options :
-Make the label font auto sizing
-change the height, or switch to dynamic height for the label
this would go something like this every time you update it:
myLabel.text = #"some text";
CGRect rect = myLabel.frame;
rect.size.height = textView.contentSize.height;// Adding.size Since height is not a member of CGRect
textView.frame = rect; //your label is now as high as its contents (the text)
-trim the text that goes into the label so it never exceeds the height of the label.
I would get rid of having your own UILabel unless absolutely necessary and dynamically adjust the cell's height based on the string size. Check out my example below:
Create the strings before loading tableview
-(void)createStrings{
newArray = [NSMutableArray array];
for(NSDictionary *dictionary in items_array){
NSString *comment = [dictionary objectForKey:(#"comment")];
NSString *first_name = [dictionary objectForKey:(#"first_name")];
NSString *combinedString = [first_name stringByAppendingString:[#": " stringByAppendingString:comment]];
[newArray addObject:combinedString];
}
}
#pragma mark - Table View Data Source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17];
}
cell.textLabel.text = [newArray objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table View Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17];
CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width, MAXFLOAT);
CGSize labelSize = [[newArray objectAtIndex:indexPath.row] sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 30;
}

iOS - UITableViewCell text alignment

I've added a tableView and dragged a table view cell into it.
in the utilities panel, I changed the style to subtitle.
I've also tried changing it in code:
- (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];
}
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.text = [myArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [myArray2 objectAtIndex:indexPath.row];
return cell;
The center alignment doesn't work!
I've tried adding a label object to the cell to have a workaround. But I don't know how to access it. even though I assigned an outlet to it, this wouldn't work:
cell.labelForCell....
What should I do?
any suggestions on how I make it work the usual way, without adding a label to the cell or something?
For the UITableViewCellStyleSubtitle text alignment cannot be changed
You will have to put a label and add your alignment to it,
To do that you could use this code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *myLabel;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
myLabel = [[UILabel alloc] initWithFrame:Your_Frame];
//Add a tag to it in order to find it later
myLabel.tag = 111;
//Align it
myLabel.textAlignment= UITextAlignmentCenter;
[cell.contentView addSubview:myLabel];
}
myLabel = (UILabel*)[cell.contentView viewWithTag:111];
//Add text to it
myLabel.text = [myArray objectAtIndex:indexPath.row];
return cell;
}
The problem with the subtitle style is that it does a [self.textLabel sizeToFit] when it lays out. When you center in a container that is the perfect size of the contents, nothing changes.
Try this. In a subclass of UITableViewCell, set your textAlignment, and use this as your layoutSubviews code:
- (void)layoutSubviews
{
[super layoutSubviews];
{
CGRect frame = self.textLabel.frame;
frame.size.width = CGRectGetWidth(self.frame);
frame.origin.x = 0.0;
self.textLabel.frame = frame;
}
{
CGRect frame = self.detailTextLabel.frame;
frame.size.width = CGRectGetWidth(self.frame);
frame.origin.x = 0.0;
self.detailTextLabel.frame = frame;
}
}
This makes the textLabel's frame full width, and thus allows the centering effect to be noticeable.
Note: since this overrides layoutSubviews, there is a performance cost as it will be called often.
I think the reason is that: the textLabel's width depends on the text length, if the text is too long to show all in a signal line, and you have already set the line break mode and set the number of lines to 0, you will find that the text alignment will be work.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (nil == cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
cell.textLabel.textAlignment = UITextAlignmentLeft;
cell.textLabel.textColor = [UIColor redColor];
cell.detailTextLabel.textColor = [UIColor greenColor];
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
cell.textLabel.numberOfLines = 0;
}
cell.textLabel.text = [NSString stringWithFormat:#"You can initialize a very long string for the textLabel, or you can set the font to be a large number to make sure that the text cann't be shown in a singal line totally:%d", indexPath.row];
return cell;
}
I think adjusting the frame will work. I had style of UITableViewCellStyleValue2 but If i have a bit lengthy text in textLabel, it getting truncated at tail and textAlignment does not work here, so thought of increase the width textLabel.
-(void)layoutSubviews{
[super layoutSubviews];
if ([self.reuseIdentifier isEqualToString:#"FooterCell"]) {
CGRect aTframe = self.textLabel.frame;
aTframe.size.width += 40;
self.textLabel.frame = aTframe;
CGRect adTframe = self.detailTextLabel.frame;
adTframe.origin.x += 70;
self.detailTextLabel.frame = adTframe;
}
}
It is impossible to change frame for textLabel and detailTextLabel in UITableViewCell
right in cellForRowAtIndexPath: method.
If you don't want to subclass your cell you can implement a small hack using
performSelector:withObject:afterDelay:
with zero delay for changing geometry right after default layoutSubviews:
[self performSelector:#selector(alignText:) withObject:cell afterDelay:0.0];
See details at here
Hi please add the following instead of your code,
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
change to
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.detailTextLabel.textAlignment = NSTextAlignmentCenter;
it will work fine.

Resources