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

  • 效果图
Swift单元格高度自适应(AutoLayout)_第1张图片
  • 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
    }

注意:约束必须准确

  • Demo下载
    Swift单元格高度自适应(AutoLayout)

你可能感兴趣的:(Swift单元格高度自适应(AutoLayout))