根据UILabel高度调整UIView的大小

时间:2019-04-30 09:46:59

标签: ios swift uiview uilabel

我看到了一些类似的答案,但是我的问题略有不同。我想创建高度为greaterThanOrEqualToConstant的视图,并在其中将UILabel放在左上方对齐(constrainttop)。如果UILabel的文本只有1行,我想使UIView的大小大于某个常数,但是如果文本有2,3,4 .. etc行(greaterThatConstant),我想根据标签高度调整此视图的大小。

2 个答案:

答案 0 :(得分:0)

您可以为此使用约束优先级。为了使视图“增长”,您可以为容器视图高度指定较小的优先级,然后标签的底部约束(到容器视图底部的距离)大于或等于您使用的任何值。当我第一次需要此功能时有点不满意:)

答案 1 :(得分:0)

查看限制:

检查图像。 : enter image description here

对于标签约束:

检查图像。 : enter image description here

代码

override func viewDidLoad() {

    let subview = UIView()
    subview.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(subview)

    //SET VIEW Constarins
    subview.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
    subview.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 25).isActive = true
    subview.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 25).isActive = true



    let lblValue = UILabel()
    lblValue.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum"
    lblValue.numberOfLines = 0
    lblValue.lineBreakMode = .byWordWrapping
    lblValue.translatesAutoresizingMaskIntoConstraints = false
    subview.addSubview(lblValue)

    //SET LABEL Constarins
    lblValue.topAnchor.constraint(equalTo: subview.topAnchor, constant: 0).isActive = true
    lblValue.leadingAnchor.constraint(equalTo: subview.leadingAnchor, constant: 0).isActive = true
    lblValue.trailingAnchor.constraint(equalTo: subview.trailingAnchor, constant: 0).isActive = true
    lblValue.bottomAnchor.constraint(equalTo: subview.bottomAnchor, constant: 0).isActive = true

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}