无法让 UILabel 自动换行

Can't get UILabel to word wrap

我已经使用 Interface Builder 使 UILabelViews 自动换行,但这是我第一次尝试以编程方式进行。我认为问题在于,尽管我正在设置:

label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0

我设置的行高可能会与这些属性冲突?

override func layoutSubviews() {
    super.layoutSubviews()
    imageViewContent.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
    imageViewContent.loadImageWithURL(imageName!)

    label.frame = CGRect(x: 0, y: 0, width: frame.size.width-10, height: 21)
    label.center = imageViewContent.center
    label.textAlignment = .center
    label.clipsToBounds = true
    label.layer.cornerRadius = 10.0
    label.textColor = .white
    label.font = UIFont(name: "AvenirNext-DemiBold", size: 15)
    label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
    label.lineBreakMode = .byWordWrapping
    label.numberOfLines = 0
    label.text = photoName
}

正如我所怀疑的那样,对标签的高度进行硬编码可以防止其自动换行。我创建了一个 labelHeight 变量,并在 class 底部添加了一个函数,用于根据我设置的内容、字体大小和 labelWidth 计算 labelHeight。代码现在工作正常:

 class NTWaterfallViewCell :UICollectionViewCell, NTTansitionWaterfallGridViewProtocol{

        var photoName = ""
        var imageName : String?
        var labelHeight: CGFloat = 0.0

        var imageViewContent : UIImageView = UIImageView()
        var label = UILabel()

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        override init(frame: CGRect) {
            super.init(frame: frame)
            backgroundColor = UIColor.lightGray
            contentView.addSubview(imageViewContent)
            contentView.addSubview(label)
        }
        override func layoutSubviews() {
            super.layoutSubviews()
            imageViewContent.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
            imageViewContent.loadImageWithURL(imageName!)

            label.text = photoName
            labelHeight = heightForText(photoName, width: frame.size.width-10)
            label.frame = CGRect(x: 0, y: 0, width: frame.size.width-10, height: labelHeight)

            label.center = imageViewContent.center
            label.textAlignment = .center
            label.clipsToBounds = true
            label.layer.cornerRadius = 10.0
            label.textColor = .white
            label.font = UIFont(name: "AvenirNext-DemiBold", size: 15)
            label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            label.lineBreakMode = .byWordWrapping
            label.numberOfLines = 0
            }

        func heightForText(_ text: String, width: CGFloat) -> CGFloat {
            let font = UIFont(name: "AvenirNext-DemiBold", size: 15)
            let rect = NSString(string: text).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
            return ceil(rect.height)
        }
 }