自动调整大小UITableViewCell,带有两个UILabel

时间:2015-01-27 06:25:25

标签: ios uitableview

我正在尝试使用自动布局来调整UITableViewCell的大小以始终适合其内容。

每个单元格包含两个垂直堆叠的标签topLabelbottomLabel。我希望两个标签都能包装并显示所有文字。

我正在使用iOS8。

这是我的代码

class MyTableViewCell: UITableViewCell {
    @IBOutlet var topLabel: UILabel!
    @IBOutlet var bottomLabel: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        topLabel = UILabel()
        topLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
        topLabel.numberOfLines = 0
        contentView.addSubview(topLabel)

        bottomLabel = UILabel()
        bottomLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
        bottomLabel.numberOfLines = 0
        contentView.addSubview(bottomLabel)

        let viewDictionary = ["topLabel": topLabel, "bottomLabel": bottomLabel]
        var constraints = [NSLayoutConstraint]()

        contentView.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "H:|-[topLabel]-|",
                options:NSLayoutFormatOptions(0),
                metrics: nil,
                views: viewDictionary))

        contentView.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "H:|-[bottomLabel]-|",
                options:NSLayoutFormatOptions(0),
                metrics: nil,
                views: viewDictionary))

        contentView.addConstraints(
            NSLayoutConstraint.constraintsWithVisualFormat(
                "V:|-[topLabel]-[bottomLabel]-|",
                options:NSLayoutFormatOptions(0),
                metrics: nil,
                views: viewDictionary))

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyTableViewController: UITableViewController, UITableViewDataSource {

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

        return 5;
    }

    override func viewDidLoad() {
        tableView.rowHeight = UITableViewAutomaticDimension
        super.viewDidLoad()
    }

    override func tableView(
        tableView: UITableView, 
        cellForRowAtIndexPath indexPath: NSIndexPath) ->
        UITableViewCell {

        let cell = MyTableViewCell(
            style: UITableViewCellStyle.Default, 
            reuseIdentifier: nil)

        cell.topLabel.text = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26"
        cell.bottomLabel.text = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"

        return cell
    }
}

但是,只有顶级标签的文字包装。结果是

enter image description here

我不确定我是否搞砸了我的约束,或者是否有我应该设置的其他属性,或者这是否是不可能的。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

cellForRowAtIndexPath中添加此行似乎可以解决问题。

cell.layoutIfNeeded()

答案 1 :(得分:0)

首先,您应该使用表视图委托heightForRowAtIndexPath来返回该行的单元格高度。其次,请将单元格内标签的行数设置为零。如果您有确认约束并返回正确的单元格高度,那么您将得到您想要的内容。

由于

相关问题