Text alignment in a UITableView

I have a cell. Whenever the text in the cell row is "(null)", I want the label to be on the right side of the cell.

Here is my code at the moment, but it does nothing. No errors, it just does not align on the right side of the cell. Any ideas?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"ChatListItem";
     NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if([[itemAtIndex objectForKey:@"user"] isEqualToString:@"(null)"]){
        cell.textLabel.textAlignment=UITextAlignmentRight;
        cell.detailTextLabel.textAlignment=UITextAlignmentRight;
    }
    cell.textLabel.text = [itemAtIndex objectForKey:@"text"];
    cell.detailTextLabel.text = [itemAtIndex objectForKey:@"user"];

   return cell;
}
0
source share
2 answers

First, did you skip the code and check the contents of the value for the user and text keys?

If everything is as expected, you should do the following:

  • Replace UITextAlignmentRightwith NSTextAlignmentRightto disable compiler warnings.
  • Explicitly install NSTextAlignmentRightand NSTextAlignmentLeft, otherwise, you will not receive the correct update in reusable cells.
  • , , . , ( ) .
+2

( UITableViewCell, ) :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ChatListItem";

    NSDictionary *dict = [_tableData objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = dict[@"text"];
    cell.detailTextLabel.text = dict[@"user"];

    if ([dict[@"user"] isEqualToString:@"(null)"]) {

        [self performSelector:@selector(alignText:) withObject:cell afterDelay:0.0];
    }

    return cell;
}

- (void)alignText:(UITableViewCell*)cell
{
    CGRect frame = cell.textLabel.frame;
    frame.origin.x = cell.frame.size.width - (frame.size.width + 10.0);
    cell.textLabel.frame = frame;

    frame = cell.detailTextLabel.frame;
    frame.origin.x = cell.frame.size.width - (frame.size.width + 10.0);
    cell.detailTextLabel.frame = frame;

    [cell setNeedsDisplay];
}

, .

0

All Articles