iOS 8 - 自动调整单元格并不总是显示所有标签文本

时间:2015-01-20 22:09:52

标签: uitableview ios8 autoresize

基本上我使用自动调整自定义表格视图单元格来显示表格视图上的数据,并且它们通常会完美地调整大小。单元格上有UILabel以显示数据,如果设备文本大小发生更改,则单元格会自动调整大小。我有时会自动调整细胞以显示所有UILabel的文本。例如,如果文字大小是中等大小,它有时并不能完全显示较长标签的所有文本,它会显示大部分文本然后显示" ..."但是如果我增加或减少文本大小,它将显示所有内容,但它可能对不同的单元格执行相同的操作。

有什么建议吗?这是我调用autoresize的代码:

- (void)viewDidAppear:(BOOL)animated
{

    [self.tableView reloadData];

    [self retrieveFromParse];

    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

}

并根据文字大小自动调整大小:

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

    static NSString *CellIdentifier = @"CellIdentifier";

    _cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (_cell == nil)
    {
        _cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    PFObject *object = [_postsArray objectAtIndex:indexPath.row];

    NSString *nameString = [object objectForKey:@"Name"];

    _cell.cellLabel.text = [NSString stringWithFormat:@"Posted by %@", nameString];
    _cell.cellPostLabel.text = [NSString stringWithFormat:@"   %@", [object objectForKey:@"Post"]];

    //The following lines are to auto resize when the text size is changed

    _cell.cellLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
    _cell.cellPostLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];

    return _cell;

}

4 个答案:

答案 0 :(得分:0)

如果有帮助

,请尝试使用 autoresizingMask
_cell.cellLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

答案 1 :(得分:0)

如果您没有在每个标签上设置preferredMaxLayoutWidth,则自动布局无法确定如何绘制多行标签。麻烦在于找出使用什么值,因为表格可以改变各种iPhone和iPad的宽度。 iPad设备,方向等。为了解决这个问题,我通常将UILabel子类化为覆盖layoutSubviews

- (void)layoutSubviews {
    [super layoutSubviews]; // 1

    self.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds); // 2

    [super layoutSubviews]; // 3
}
  1. super的第一次调用正确地确定了标签的宽度。
  2. 使用正确的宽度,将preferredMaxLayoutWidth设置为正确的值。
  3. 执行另一个布局传递以使用其最终和正确的属性呈现标签。

答案 2 :(得分:0)

如果您使用autolayout,我会为您提供解决方案。我不确定这是完美的,但在这里(Swift):

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    // configure your cell
    cell.layoutIfNeeded()      
}

P.S。如果我没有使用layoutIfNeeded,并且如果我旋转我的设备然后将其转回到肖像,则必须标记布局,例如一个单元格中有2个或更多字符串。

没有找到导致这种情况发生的原因,因为(我在我的项目中使用了更多的原型单元格)其他类型的单元格是可以的,但是它们的标签具有类似的约束和设置。

答案 3 :(得分:-1)

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 66
}
对于UITableViewCellStyle.Default单元格,

在8.4.1上运行正常