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
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 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 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)
I am creating UITableView, where each cell size will b calculated based on the text I input.
I am Calculating size of Cell in heighForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [tableData objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(210.0f, 20000.0f);
size = [text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
height = MAX(size.height, 44.0f);
return height + (CCM * 2);
}
this is how I am calculating height for each cell, now my question is - I want to add image to each cell like comment box? like this
Click here to see comment boxes I am looking for
You can see these kind of comment boxes
what I did is I made my image into two parts
first one has top part which is working well on every cell starting image is coming
now while fixing bottom part me facing problem
for small text in cell UILable its working well
when size of text in UILabel increased it's not getting properly adjusted
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = #"cell";
NSLog(#"index path %d", indexPath.row);
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[[MyTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell.cellBackgroundBottom setFrame:CGRectMake(75.0f, 92.0f, 228.0f, height + 25.0f)];
[cell.cellContent setText:(NSString*)[tableData objectAtIndex:[indexPath row]]];
[cell.cellContent sizeToFit];
CGRect theFrame = [cell.cellContent frame];
theFrame.size.width = 210.0f;
[cell.cellContent setFrame: theFrame];
return cell;
}
I have created one UITableView subclass naming MYTableCell where I have defined what all I need inside my each cell.
// Creating UILabel for cell content or comments block
cellContent = [[UILabel alloc]initWithFrame: CGRectMake( 90.0f, 15.0f, 210.0f, 60.0f)] ;
[cellContent setLineBreakMode:UILineBreakModeWordWrap];
cellContent.numberOfLines = 0;
[cellContent setMinimumFontSize:15.0f];
[cellContent setBackgroundColor:[UIColor clearColor]];
// [cellContent setTextColor:[UIColor colorWithRed:73.0f green:73.0f blue:73.0f alpha:1.0f]];
[cellContent setFont:[UIFont fontWithName:#"Helvetica" size:12.0f]];
cellContent.textAlignment = UITextAlignmentLeft;
[cellContent setTag:1];
[self addSubview:cellContent];
[cellContent release];
cellBackgroundTop = [[UIImageView alloc] initWithFrame:CGRectMake(60.0f, 5.0f, 243.0f, 13.5f)];
[cellBackgroundTop setImage:[UIImage imageNamed:#"comments.png"]];
[self addSubview:cellBackgroundTop];
[cellBackgroundTop release];
cellBackgroundBottom = [[UIImageView alloc] initWithFrame:CGRectZero];
[cellBackgroundBottom setImage:[UIImage imageNamed:#"Untitled-1_09.png"]];
[self addSubview:cellBackgroundBottom];
[cellBackgroundBottom release];
I got answer for my question
. This is what i have to do in my cellForRowAtIndexPath
NSString *text = [tableData objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(210.0f, 20000.0f);
CGSize size1 = [text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height1 = MAX(size1.height, 44.0f);
[cell.cellBackgroundBottom setFrame:CGRectMake(75.0f, 18.0f, 228.0f, height1 + 10.0f)];
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.