单行文本在UILabel中占两行

Upv*_*ote 4 uitableview uilabel ios swift

在此输入图像描述

正如你在图片中看到的那样,中间单元格有一个消耗两行的UILabel,但文本实际上是一行.似乎如果文本只需要几个字符来创建一个新行,iOS似乎已经有两行.这很奇怪.

这是我创建标签的方式:

self.titleLabel.lineBreakMode = .ByTruncatingTail
self.titleLabel.numberOfLines = 0
self.titleLabel.textAlignment = .Left
Run Code Online (Sandbox Code Playgroud)

约束设置一次:

self.titleLabel.autoPinEdgeToSuperviewEdge(.Top)
self.titleLabel.autoPinEdgeToSuperviewEdge(.Leading)
self.titleLabel.autoPinEdgeToSuperviewEdge(.Trailing)
self.titleLabel.autoPinEdgeToSuperviewEdge(.Bottom)
Run Code Online (Sandbox Code Playgroud)

奇怪的是,当滚动表格以便奇数单元格消失并再次向后滚动时,它具有正常高度.滚动后:

在此输入图像描述

任何想法都错了吗?我使用的是swift,xcode6.1和iOS8.1

TableViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.registerClass(CityTableViewCell.self, forCellReuseIdentifier:"cell")
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 52
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let cell: CityTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as? CityTableViewCell {
        // Configure the cell for this indexPath
        cell.updateFonts()
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        if indexPath.row == 1 {
            cell.titleLabel.text = "Welcome to city 17, Mr. Gordon F."
        } else {
            cell.titleLabel.text = "Lamar!!!"
        }
        // Make sure the constraints have been added to this cell, since it may have just been created from scratch
        cell.setNeedsUpdateConstraints()
        cell.updateConstraintsIfNeeded()

        return cell
    }
    return UITableViewCell();
}
Run Code Online (Sandbox Code Playgroud)

val*_*fer 6

我想你遇到了这个错误:http://openradar.appspot.com/17799811.标签未preferredMaxLayoutWidth正确设置.

我选择的解决方法是UITableViewCell使用以下类进行子类化:

class VFTableViewCell : UITableViewCell {

    @IBOutlet weak var testoLbl: UILabel!

    //MARK: codice temporaneo per bug http://openradar.appspot.com/17799811

    func maxWidth() -> CGFloat {

        var appMax = CGRectGetWidth(UIApplication.sharedApplication().keyWindow.frame)

        appMax -= 12 + 12    // borders, this is up to you (and should not be hardcoded here)

        return appMax
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        // MARK: Required for self-sizing cells.
        self.testoLbl.preferredMaxLayoutWidth = maxWidth()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // MARK: Required for self-sizing cells
        self.testoLbl.preferredMaxLayoutWidth = maxWidth()
    }
}
Run Code Online (Sandbox Code Playgroud)

OP-注意:

似乎自动布局不能正确计算UILabel布局的宽度.在我的UITableViewCell子类中将首选宽度设置为父级宽度解决了我的问题:

self.titleLabel.preferredMaxLayoutWidth = self.frame.width
Run Code Online (Sandbox Code Playgroud)

在SO上找到:https://stackoverflow.com/a/19777242/401025