Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center label in UITableViewCell

i'm trying to programmatically center a Custom UILabel into a UITableViewCell. The problem is it does not seem to center probably. I'm using this code:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    chatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) cell = [[chatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    float yPos = (CGRectGetHeight(cell.contentView.frame) - CGRectGetHeight(cell.homeTeamLabel.frame)) / 2;

    cell.homeTeamLabel = [[UILabel alloc] initWithFrame:CGRectMake(22.0, yPos, 220.0, 15.0)];
    cell.homeTeamLabel.text = [items objectAtIndex:indexPath.row];
    cell.homeTeamLabel.font = [UIFont systemFontOfSize:14.0];
    cell.homeTeamLabel.textColor = [UIColor blackColor];
    [cell.contentView addSubview:cell.homeTeamLabel];


    return cell;
}

And here is a picture of how it looks. As you can see its not centered. How can i center it?

enter image description here

like image 517
user3258468 Avatar asked Dec 19 '22 18:12

user3258468


1 Answers

cell.homeTeamLabel.textAlignment = UITextAlignmentCenter;

My bad. It's Sunday morning and I need more coffee!

iOS6 and above uses

cell.homeTeamLabel.textAlignment = NSTextAlignmentCenter;
like image 161
sangony Avatar answered Jan 12 '23 15:01

sangony