alignmentUITableView中的文本

我有一个单元格。 只要单元格行中的文本等于“(null)”,我希望标签位于单元格的右侧。

这是我目前的代码,但它没有做任何事情。 没有错误,它只是不alignment到单元格的右侧。 有任何想法吗?

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

首先,你是通过代码来检查键“用户”和“文本”的值的内容?

如果一切如预期的那样,您应该执行以下操作:

  1. UITextAlignmentRightreplaceUITextAlignmentRight以使编译器警告NSTextAlignmentRight
  2. 显式设置NSTextAlignmentRightNSTextAlignmentLeft ,否则在循环单元中不会得到正确的更新。
  3. 最后,确保标签的宽度是固定的。 否则,标签的宽度将基于其内容,以便alignment(在标签内)失去效果。

你的情况唯一的工作解决scheme(当然没有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]; } 

至于我,我最好做一个子类。