Swift单元格高度自适应(AutoLayout)

  • 效果图
  • Apple官方文档解释layoutSubviews()

The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.
Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.
You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.

  • layoutSubviews的作用:
    对subviews重新布局。想要更新子视图的位置的时候,可以通过调用layoutSubviews方法,即可以实现对子视图重新布局。
  • layoutSubviews以下情况会被调用:
    1. 直接调用setLayoutSubviews()
    2. addSubview添加子类
    3. frame发生改变
    4. 滑动UIScrollView
    5. 旋转Screen
    6. 改变UIView大小
  • 注意:
    不要直接调用layoutSubviews。如果你想强制更新布局,可以调用setNeedsLayout方法;如果你想立即更新视图的布局,可以调用layoutIfNeeded方法。
  • 重写单元格layoutSubviews方法:
override func layoutSubviews() {
        super.layoutSubviews()
        self.contentView.setNeedsLayout()
        self.contentView.layoutIfNeeded()
        ////对于单行label,这个属性不用设置;对于多行label,则需要设置最大autolayout宽度,如果文本超出这个属性指定的宽度,则会自动换行
        self.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentLabel.frame)
    }
  • 实现ViewController中heightForRowAtIndexPath方法
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let hsCell = tableView.dequeueReusableCellWithIdentifier(cellIdentfier) as? HSCell
        var tempCell: HSCell
        hsCell != nil ? (tempCell = hsCell!) : (tempCell = HSCell())
        tempCell.contentLabel.text = dataSource[indexPath.row].content
        tempCell.bounds = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), CGRectGetHeight(tempCell.bounds))
        tempCell.layoutIfNeeded()
        return tempCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 1
    }

注意:约束必须准确

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容