UITableView,cell使用autolayout,contentSize不準确的問題
當使用autolayout讓cell自動算高時,會設定
table.estimatedRowHeight = 100;
table.rowHeight = UITableViewAutomaticDimension;
這時候擷取contenSize 得到是以estimatedRowHeight 為cell高度算出來的,很明顯是不準确的。
而且有時候就算在layoutsubviews 方法裡也得不到正确的contentSize
如何解決:
- 先調用reloadData
- 再用GCD回到主線程
-
在主線程裡加入UIView動畫,調layoutIfNeeded
在主線程block裡即可得到正确的contentSize
代碼如下:
_tableViewConstraint.constant = CGFloat_MAX;
[_tableView reloadData];
[_tableView layoutIfNeeded];
_tableViewConstraint.constant = _tableView.contentSize.height;
原理: 先給tableView設定一個極大值,讓tableView有空間來處理各cell大小。