我无法自动包装UIlabel

时间:2019-09-11 04:05:04

标签: ios swift uilabel

我有以下代码

import UIKit

class BookDetailTableViewCell: UITableViewCell {

    let bookImage = UIImageView()
    let bookTitle = UILabel()
    let bookDesc = UILabel()
    let bookAuthor = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)


        contentView.addSubview(bookImage)
        contentView.addSubview(bookTitle)
        contentView.addSubview(bookDesc)
        contentView.addSubview(bookAuthor)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        var frame = bookImage.frame
        frame.size.height = 150
        frame.size.width = 100
        frame.origin.x = 10
        frame.origin.y = 10
        bookImage.frame = frame

        var aframe = bookTitle.frame
        aframe.size.height = 26
        aframe.size.width = self.frame.size.width - 140
        aframe.origin.x = 130
        aframe.origin.y = 20
        bookTitle.frame = aframe
        bookTitle.textColor = UIColor(red:0.52, green:0.80, blue:0.84, alpha:1.0)
        bookTitle.font = UIFont(name: "SFProText-Bold", size: 16);


        bookDesc.textColor = UIColor(red:0.25, green:0.31, blue:0.40, alpha:1.0)
        bookDesc.lineBreakMode = NSLineBreakMode.byWordWrapping
        bookDesc.numberOfLines = 0
        bookDesc.font = UIFont(name: "Avenir-Book", size: 13);

        var bframe = bookDesc.frame
        bframe.size.height = 23
        bframe.size.width = self.frame.size.width - 140
        bframe.origin.x = 130
        bframe.origin.y = 56
        bookDesc.frame = bframe

        var cframe = bookAuthor.frame
        cframe.size.height = 23
        bookAuthor.textColor = UIColor.black
        cframe.size.width = self.frame.size.width - 140
        cframe.origin.x = 130
        cframe.origin.y = self.frame.size.height - 40
        bookAuthor.frame = cframe
        bookAuthor.font = UIFont(name: "SFProText-Regular", size: 13);
    }

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

UILabel的自动换行不对标签bookDesc进行自动换行。有人知道为什么吗?使用XCode 10.0。雨燕5.0

我正在以编程方式实现UILabel,而不使用情节提要。

2 个答案:

答案 0 :(得分:0)

您怎么能说换行模式不起作用?因为您在以下代码中提供了23的固定高度。

    var bframe = bookDesc.frame
    bframe.size.height = 23
当文本较大时,

换行模式不会为您增加高度,因为您有两个选择,要么对所有视图应用有效约束,要么根据文本计算高度并更改标签的高度以编程方式

如果发现约束困难,请使用stackview

希望这将帮助您了解代码问题

答案 1 :(得分:-1)

尝试在属性检查器下选择自动换行选项。