- 效果圖
- 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)