UILabel text alignment right

27,074

Solution 1

Because you are using sizeWithFont and then setting your frame to that size, your text is aligned right. Try added a background color of light gray to your label to see what I'm talking about. Your label should be set to the same size as your table cell and allow the text to flow inside it. Then it will align to the right.

Update with sample

- (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
}

Solution 2

Right alignment for label

yourLabel.textAlignment = NSTextAlignmentRight;

Solution 3

Finally I have fix my problem. I was doing small mistake

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

I just remove size.width and give my specific coordinate 200 after that the text is align right.

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

Thanks all for your response

Share:
27,074
Alok Srivastava
Author by

Alok Srivastava

iPhone developer

Updated on September 18, 2020

Comments

  • Alok Srivastava
    Alok Srivastava over 3 years

    I want that my text should be align right.

    - (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 align right Please Help