首页 文章

如何使用自动布局约束在表格单元格中拟合具有可变大小的2个标签,使用estimatedHeightForRowAtIndexPath估计高度

提问于
浏览
1

我有以下布局与以下约束 .

当我运行它时,它看起来就像所希望的那样 . 单元格高度调整为适合所有文本 .

但是,我在问题导航器中看到以下警告,我不明白为什么 .

2 views are vertically ambiguous

  • Height and vertical position are ambiguous for View

  • Height is ambiguous for View

布局:
enter image description here

约束:

  • 视图(单元格中所有元素的单元格包装视图)

enter image description here

  • 视图(选项1包装器视图)

enter image description here

  • 按钮(选项1按钮)

enter image description here

  • 标签(选项1标签)

enter image description here

  • 查看(选项2包装视图)

enter image description here

  • 按钮(选项2按钮)

enter image description here

  • 标签(选项2标签)

enter image description here

表视图控制器代码:

import UIKit

class SelectionTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Hide navigation bar
        self.navigationController?.navigationBarHidden = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: Hide status bar
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

}

2 回答

  • -1

    故事板似乎在抱怨,因为它没有_749816的视图,它不知道你将在运行时使用 estimatedHeightForRowAtIndexPath 提供高度 . 所有约束都与超视图或其他视图相关,因此有无限的方法来满足这些要求 .

    禁止这些警告的最简单方法是给单元格的内容视图一个明确的高度,然后在右侧导航器上检查该约束的“在构建时删除”框(在左侧导航器中找到它,然后单击它那里) .

    enter image description here

    给出一个显式数字将允许编译器为这些视图的高度和y位置提供显式值,这些值应解决您获得的警告 . 然后删除该约束应该允许单元格使用您实现的方法在代码中动态调整大小 .

  • 0

    我认为你的按钮对他们的超级视图边缘没有任何顶部和底部约束 . 因此,他们的超级视图(两个包装器视图)不知道它们的高度 .

相关问题