问题
I have an app with several UITableView controllers. Running on iOS 8.x, the height of all the cells in each table would resize to fit the content of the cell (all contain just a UILabel with plain text). Now when running on iOS 9, every cell on every table is only one line tall. This is with both dynamic and static tables. I've scoured the UIKit diffs document and done extensive searching, but I can't find the right combination of things to get anything other than a height of one line in all the cells in all the tables.
回答1:
I've run into a similar case. The trick seems to be to implement the dynamic sizing via UITableView
's delegate methods explicitly. Even though settings automatic
in storyboards is supposed to work - it doesn't. The solution is to provide UITableViewAutomaticDimension
explicitly via the delegate method and then provide estimated cell sizes as you normally would:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
/* Return an estimated height or calculate
* estimated height dynamically on information
* that makes sense in your case.
*/
return 200.0f;
}
If anyone knows precisely why this is necessary in iOS 9 and how it differs from iOS 8, I'd love to hear it.
回答2:
We can use "UITableViewAutomaticDimension" in iOS 8 to implement the dynamic sizing explicitly by using following two properties:-
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableViewAutomaticDimension
Then add following code in "cellForRowAtIndexPath" method before return cell.
cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()
And for iOS 9 we can add tableView's delegate method:-
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
回答3:
There is a UIStackView issue on iOS 9-10 when using layoutMargins
extension UIStackView {
open override func didMoveToSuperview() { // a workaround for stackview issues on iOS 9-10
super.didMoveToSuperview()
if #available(iOS 11.0, *) { } else {
layoutMargins = self.layoutMargins
}
}
}
来源:https://stackoverflow.com/questions/32528976/all-uitableviewcells-become-one-line-in-height-on-ios-9