尝试自动调整两个标签在单元格中垂直对齐的大小,这可能吗?

storyboard中,我们必须设置autolayout,因为我要自动调整两个标签的大小(一个在另一个标签的顶部)。

我无法设置每个高度,以使情节提要板不知道这两个标签的高度是多少,因此显示autolayout错误。

ios - 两个标签在tableView单元格中垂直对齐自动调整大小迅速-LMLPHP

如果我单击“添加缺少的约束”按钮,则会为“字幕”添加高度

或者我可以为“标题”而不是“字幕”设置高度,

或使“标题”等于“字幕”,它将仍然接受。

ios - 两个标签在tableView单元格中垂直对齐自动调整大小迅速-LMLPHP

结果如下:

ios - 两个标签在tableView单元格中垂直对齐自动调整大小迅速-LMLPHP

解决方法是将这两个单独的单元分开。
有更好的解决方案吗?还是我只是忘记做任何事情?

附言我在iOS 10.3中使用Xcode 8。

最佳答案

尝试为两个标签设置适当的约束:

故事板-:

第一个label-的约束:

ios - 两个标签在tableView单元格中垂直对齐自动调整大小迅速-LMLPHP

第二个label-的约束:

ios - 两个标签在tableView单元格中垂直对齐自动调整大小迅速-LMLPHP

控制器类(对table view使用自动尺寸)-:

class ViewController1: UIViewController {

    var dataForTableView:[ProductImage]?

    @IBOutlet weak var secondTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        secondTable.estimatedRowHeight = 96
        secondTable.rowHeight = UITableViewAutomaticDimension
        // CHECK FOR DATA

        //print(dataForTableView?[0].url as Any)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController1 : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! testingCell2
        cell.backgroundColor = UIColor.blue;
        cell.secondLabel.text = "agfhjsgfhjsgdshgfhjsfjhvhssajs hjfbvhjfbvjhfgafgfhlgkaghkfakfhkflbvhfbvhfvbhfv ah fvfhbvfjhvbfhdavhfvhv"
        return cell
    }

    // Number of sections in table

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }// Default is 1 if not implemented

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return UITableViewAutomaticDimension
    }

}


输出-:

ios - 两个标签在tableView单元格中垂直对齐自动调整大小迅速-LMLPHP

我希望这是您要寻找的东西,如果有任何问题,请告诉我。

10-08 15:44