Swift_Learn首页投稿(暂停使用,暂停投稿)iOS进阶指南

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

2016-08-02  本文已影响496人  ZhHS

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.

override func layoutSubviews() {
        super.layoutSubviews()
        self.contentView.setNeedsLayout()
        self.contentView.layoutIfNeeded()
        ////对于单行label,这个属性不用设置;对于多行label,则需要设置最大autolayout宽度,如果文本超出这个属性指定的宽度,则会自动换行
        self.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentLabel.frame)
    }
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
    }

注意:约束必须准确

上一篇 下一篇

猜你喜欢

热点阅读