How do I support self sizing cells on iOS7?

﹥>﹥吖頭↗ 提交于 2019-12-30 00:59:29

问题


With the release of iOS8 I have designed my table view with cells taking advantage of self sizing cells. But I need my tables to work in iOS7 as well. How do I do that? Is there a way to check whether self sizing cells is supported or not in runtime, or can I implement some table delegate methods in my controller which will not be called in iOS7?

If I try my table with self sizing cells in iOS7 I get errors on the console like this:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7fc912d1d5a0 V:|-(>=11)-[UILabel:0x7fc912d13900]   (Names: '|':UITableViewCellContentView:0x7fc912d13400 )>",
    "<NSLayoutConstraint:0x7fc912d1d6b0 V:[UILabel:0x7fc912d13900]-(11)-|   (Names: '|':UITableViewCellContentView:0x7fc912d13400 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7fc912d24d80 h=--& v=--& V:[UITableViewCellContentView:0x7fc912d13400(0.5)]>"
)

回答1:


This is the solution I have found thus far, but it requires checking for specific version number rather than capability. You only set UITableViewAutomaticDimension if you have iOS 8 or higher as version:

override func viewDidLoad() {

    if NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1 {
        self.tableView.estimatedRowHeight = 80
        self.tableView.rowHeight = UITableViewAutomaticDimension
    }
}

For iOS 7 you need to calculate a height for each cell. But if you are on iOS 8 you can return UITableViewAutomaticDimension as the height:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1 {
        return UITableViewAutomaticDimension
    }
    return 50 // Or whatever calculated value you need for cell height
}



回答2:


For iOS versions older than 8.0, you can always write the usual heightForRowAtIndexPath method where you create a cell, run an auto layout pass on it and then return the actual height.



来源:https://stackoverflow.com/questions/26282051/how-do-i-support-self-sizing-cells-on-ios7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!