【问题标题】:View has changed when a TableView cell is selected for iOS为 iOS 选择 TableView 单元格时视图已更改
【发布时间】:2015-07-16 08:42:16
【问题描述】:

我使用自动布局创建了一个自定义表格视图单元格,如下图所示

应用启动后,一切正常。但是当我滚动 tableview 或选择一个视图时,单元格的布局将会改变。 发生了什么?

代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
[cell.textLabel setText: textToSHow];

cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
[cell setNeedsLayout];
[cell layoutIfNeeded];

CGSize fitSize = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return fitSize.height;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:cellIdent];
[cell.textLabel setText:textToSHow];
return  cell;
}

运行应用程序:

当一个单元格被选中时:

非常感谢!

【问题讨论】:

  • 当一切都设置为自动布局时,你为什么要计算行的height
  • 表格视图有一个名为:heightforrow 的数据源,所以我需要自己计算行高。
  • 这不是必需的方法...您可以使用该方法或自动布局...如果您想使用代码,我认为您可以删除约束。
  • 我不认为你可以通过这种方式成功,你能提供可以正确运行的完整源代码吗?

标签: ios objective-c uitableview autolayout


【解决方案1】:

iOS 8+ 解决方案(使用自动布局):

将此添加到您的viewDidLoad

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

并且删除tableView:heightForRowAtIndexPath:方法。

【讨论】:

    【解决方案2】:

    我认为您需要更改现有实现中的一些代码。通过替换现有代码来尝试此操作。

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        CGSize fitSize = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        return fitSize.height;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 3;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        TableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:cellIdent forIndexPath:indexPath];
        [cell layoutIfNeeded];
    
        [cell.textLabel setText:textToSHow];
        return  cell;
    }
    

    【讨论】:

    • 感谢您的帮助。但是滚动表格视图时我遇到了同样的问题
    • 看看 heightForRowAtIndexPath 将在您滚动表格视图时被调用。可能您用来确定高度的方法不正确。尝试通过计算根据宽度计算文本的高度。这是您的问题的主要原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多