swift - 根据内容调整 UILabel 高度?

标签 swift xcode uilabel constraints

我有一个自定义 CollectionViewCell 类,其中包含一个标签和一个图像。基本上,图像将被限制在单元格的左侧、顶部和右侧。但是,我希望它的高度根据 UILabel 的高度而变化,而 UILabel 的高度又取决于其中的内容。以下是我的尝试:

导入UIKit

类 CustomCollectionViewCell:UICollectionViewCell {

override init(frame: CGRect) {

    super.init(frame: frame)

    backgroundColor = .yellow

}

required init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

}

convenience init(cellTextTile text: String) {

    self.init()

}

func setupCustomCellElements(cellImageName image: String, cellTitleTextColour textColour: UIColor, cellTitleTextSize textSize: CGFloat, cellTitleFontType fontType: String, cellTitle title: String) {

    let cellImage: UIImageView = {

        let imageView = UIImageView()

        imageView.backgroundColor = .clear

        imageView.image = UIImage(named: image)

        imageView.translatesAutoresizingMaskIntoConstraints = false

        return imageView

    }()

    let cellTitle: UILabel = {

        let label = UILabel()

        label.textColor = textColour

        label.font = UIFont(name: fontType, size: textSize)

        label.text = title

        label.textAlignment = .center

        label.frame.size = CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude)

        label.numberOfLines = 0

        label.lineBreakMode = NSLineBreakMode.byWordWrapping

        label.sizeToFit()

        label.translatesAutoresizingMaskIntoConstraints = false

        return label

    }()

    addSubview(cellImage)

    addSubview(cellTitle)

    NSLayoutConstraint.activate([

        cellTitle.bottomAnchor.constraint(equalTo: bottomAnchor),

        cellTitle.leftAnchor.constraint(equalTo: leftAnchor),

        cellTitle.rightAnchor.constraint(equalTo: rightAnchor),

        cellImage.bottomAnchor.constraint(equalTo: cellTitle.topAnchor),

        cellImage.topAnchor.constraint(equalTo: topAnchor),

        cellImage.leftAnchor.constraint(equalTo: leftAnchor),

        cellImage.rightAnchor.constraint(equalTo: rightAnchor)

        ])

}

}

但是,使用上面的代码我没有得到我正在寻找的行为。我希望 UIlabel 的高度根据其内容而改变。并反过来对图像的高度进行相应调整?

问候, 沙迪。

最佳答案

您需要对 imageView 进行高度限制

cellImage.heightAnchor.constraint(equalToConstant: 50), // or any value 

也不要在方法 setupCustomCellElements 中添加属性,使它们成为实例变量,并将它们添加到 init 函数中

<小时/>

最好也将 View 添加到

contentView.addSubview(cellImage) 
contentView.addSubview(cellTitle)

并用它构建约束

关于swift - 根据内容调整 UILabel 高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55986127/

相关文章:

ios - 如何在 TableView Controller 中放置文本字段以读取内容

json - 将 JSON 数据返回给 Swift 中的调用类

ios - Swift 2 prefersStatusBarHidden() 未调用

ios:<错误>:CGAffineTransformInvert:奇异矩阵

ios - Xcode UI 测试正在生成并运行新应用程序 MyAppUITests?

swift - 如何将 UIImage 放在 UILabel 前面 - Swift

ios - 如何使用自动布局更改标签位置

ios - UILabel 从垂直中心开始

ios - 如何在不调用 viewdidload 的情况下第二次显示我的 View Controller ?

XCode 更改注释快捷方式的默认行为