【问题标题】:Adjusting UILabel height depending on contents?根据内容调整 UILabel 高度?
【发布时间】:2019-05-04 19:31:22
【问题描述】:

我有一个自定义 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 的高度根据其内容而改变。并反过来对图片的高度进行相应的调整?

问候, 沙迪。

【问题讨论】:

  • 你得到了什么?
  • UILabel 的高度没有改变,因此图像的高度也没有改变。

标签: swift xcode uilabel constraints


【解决方案1】:

你需要一个 imageView 的高度限制

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

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


最好也将视图添加到

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

并用它来构造约束

【讨论】:

  • 非常感谢,这正是我所做的,它解决了我的问题。我使用了一个常量值,我创建了一个函数来计算:)
猜你喜欢
  • 1970-01-01
  • 2012-08-03
  • 2010-12-18
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多