简体   繁体   中英

How to align center cell text in Iphone?

I am unable to align center cell text. I wonder if it may be a problem with XML ?

I am create an UILabel, aligning it to the center and adding it to the cell. This is an example of my code:

 if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *lblMenuTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 250, 30)];
NSString *sectionString = [NSString stringWithFormat:@"%@",[[arrDataSection objectAtIndex:indexPath.row] valueForKey:kCasesName]];
[lblMenuTitle setText:sectionString];
[lblMenuTitle setTextAlignment:UITextAlignmentCenter];
lblMenuTitle.font = [UIFont boldSystemFontOfSize:18.0];
    [lblMenuTitle setNumberOfLines:0];
    [lblMenuTitle setTag:[[NSString stringWithFormat:@"1%d",indexPath.row] intValue]];
    [lblMenuTitle setLineBreakMode:UILineBreakModeWordWrap];
[lblMenuTitle setBackgroundColor:[UIColor clearColor]];
[cell addSubview:lblMenuTitle];

CGRect frame;
    CGSize size;

    frame = CGRectMake(20, 5, 250, 30);

    size = [lblMenuTitle.text sizeWithFont:[UIFont systemFontOfSize:18.0]
                               constrainedToSize:CGSizeMake(frame.size.width, 9999)
                                   lineBreakMode:UILineBreakModeWordWrap];

    frame.size = CGSizeMake(size.width+20, size.height);

    lblMenuTitle.frame = frame;
  }

  return cell;

You compute the size of your text ( size = [lblMenuTitle.text sizeWithFont:…] ) and modify the frame of your lblMenuTitle label so that its width is the size of the text (+20px)…

So it is quite normal that the text is not centered in your cell : the text is centered in your UILabel ( [lblMenuTitle setTextAlignment:UITextAlignmentCenter] ) but the label is the same width as the text itself ! So if the text is 100px wide, your label will be 120px wide… but the origin of its frame will still be x=20 !

Either keep your label width as large as your cell width, and let the text alignment do its job of centering the text into the label, or if you still want to resize your label the same width as your text, then center its frame too ( lblMenuTitle.center = cell.center for example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM