UIStackView and multi-line labels in a UITableViewCell

我与影子孤独终老i 提交于 2019-12-07 06:09:09

问题


I want to have a custom UITableViewCell with a number of vertically stacked UILabels all of which can contain text that wraps multiple lines. With the new UIStackView in iOS9 and the cell self-sizing mechanism I thought this would be straightforward, but I can't get it to work. I am using Xcode 7beta3.

I created a simple test app. This is the setup in IB:

The UIStackView is vertical with UIStackViewDistribution.Fill and UIStackViewAlignment.Fill but I have basically tried all the combinations without success.

The UILabels have numberOfLines = 0 and lineBreakMode = .ByWordWrapping.

The code:

class Cell: UITableViewCell {

    @IBOutlet var label1: UILabel!
    @IBOutlet var label2: UILabel!
}

class MasterViewController: UITableViewController {

    struct Data {
        let label1: String
        let label2: String
    }

    var objects = [Data]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 60

        createData()
    }

    private func createData() {

        for ii in 0 ..< 20 {

            let data = Data(label1: "\(ii): hello world this is a longer string that should wrap without going weird", label2: "label2 has lots of writing as well and so should wrap onto multiple lines")
            objects.append(data)
        }
    }

    // MARK: - Table View

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

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

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! Cell
        let data = objects[indexPath.row]

        cell.label1?.text = data.label1
        cell.label2?.text = data.label2

        return cell
    }
}

I wonder if there is a bug in the beta, because sometimes one of the labels wraps while the other doesn't.

For example I tried nesting the UIStackView in another UIStackView as follows:

I made no code changes at all. Now one label wraps while the other does not:

Any help would be greatly appreciated!


回答1:


The problem is at the time of cell initialisation the width of the cell will be 600 by default so it will calculate the height of the row based on 600 width. This is because cell is created in the storyboard with size classes.

i think it will be a bug in the beta version and as a solution of this take your cell in xib and then use . It will work fine.



来源:https://stackoverflow.com/questions/31457469/uistackview-and-multi-line-labels-in-a-uitableviewcell

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