UIView dynamic height depending on Label Height

后端 未结 6 1046
再見小時候
再見小時候 2021-01-15 05:35

I have a Label which takes dynamicaly some data from database. These data are strings which can sometimes be 3-4-5 rows etc. So this labe is inside a UIView.



        
6条回答
  •  醉酒成梦
    2021-01-15 05:58

    Bellow is working solution of your problem. I used autoLayout. In testView you don't set heightAnchor

    let testView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = UIColor.redColor()
        return view
    }()
    
    let testLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "jashfklhaslkfhaslkjdhflksadhflkasdhlkasdhflkadshkfdsjh"
        return label
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        view.addSubview(testView)
        testView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
        testView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
        testView.widthAnchor.constraintEqualToConstant(100).active = true
    
    
        testView.addSubview(testLabel)
        testLabel.topAnchor.constraintEqualToAnchor(testView.topAnchor, constant: 10).active = true
        testLabel.leftAnchor.constraintEqualToAnchor(testView.leftAnchor, constant: 10).active = true
        testLabel.bottomAnchor.constraintEqualToAnchor(testView.bottomAnchor, constant: -10).active = true
        testLabel.rightAnchor.constraintEqualToAnchor(testView.rightAnchor, constant: -10).active = true
    
    }
    

提交回复
热议问题