UILabel text alignment rule

I want my text to be correctly aligned.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"lisn"];
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"lisn"] autorelease];
CGSize  textSize = { 210.0, 10000.0 };
CGSize size = [[gMessageArray objectAtIndex:indexPath.row] sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];

UILabel *lisnerMessage=[[[UILabel alloc] init] autorelease];
lisnerMessage.backgroundColor = [UIColor clearColor];
[lisnerMessage setFrame:CGRectMake(75 ,20,size.width + 5,size.height+2)];
lisnerMessage.numberOfLines=0;
lisnerMessage.textAlignment=UITextAlignmentRight;
lisnerMessage.text=[gMessageArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:lisnerMessage];
return cell
}

but my text is not aligned correctly Please help

+5
source share
4 answers

Since you use sizeWithFont and then set your frame to this size, your text is aligned to the right. Try adding a light gray background color to your label to find out what I'm talking about. Your label should be set to the same size as the table cell, and allow the flow of text inside it. Then it will align to the right.

Update with an example

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"lisn"];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"lisn"];

    UILabel *lisnerMessage = [[UILabel alloc] init];
    lisnerMessage.backgroundColor = [UIColor clearColor];
    [lisnerMessage setFrame:cell.frame];
    lisnerMessage.numberOfLines = 0;
    lisnerMessage.textAlignment = NSTextAlignmentRight;
    lisnerMessage.text = [gMessageArray objectAtIndex:indexPath.row];
    [cell.contentView addSubview:lisnerMessage];

    return cell
}
+9
source

Correct alignment for the tag

yourLabel.textAlignment = NSTextAlignmentRight;
+6
source

, . .

[lisnerMessage setFrame:CGRectMake(75 ,20,size.width + 5,size.height+2)];

size.width 200, .

[lisnerMessage setFrame:CGRectMake(75 ,20,200,size.height+2)];

+1

Why don't you just make a shortcut in the interface builder / storyboard and choose the "align right" option? Then connect it as a property called lisnerMessage and lisnerMessage.text=[gMessageArray objectAtIndex:indexPath.row]; That would greatly reduce how much code you write and definitely work.

0
source

All Articles