Swift iOS -How to set UIView's Height Anchor <= To A Label's Intrinsic Text Size? 'NSLayoutConstraint' is not convertible to 'Bool'

Viewed 9628

I have a programmatic view with a label inside of it that I'm pinning to the bottom of the navBar. There will be dynamic text inside of the label and I want the view the label is in to be the at least 64 pts or bigger if the height of text makes it smaller.

The intrinsic size of the text from this label sets the view at a noticeable height.

setViewAndLabel(dynamicText: "Unknown Error\nPlease try your request again\Error: 123")

enter image description here

However the intrinsic size of this text makes the height to small:

setViewAndLabel(dynamicText: "Message Deleted!")

enter image description here

The Message Deleted! should be more along the lines of:

enter image description here

I used some return keys to set it like that but I don't think that's the correct way to go because different messages will get generated:

setViewAndLabel(dynamicText: "\nMessage Deleted!\n")

I also tried:

if myView.heightAnchor.constraint(lessThanOrEqualToConstant: 64){
     myView.heightAnchor.constraint(equalToConstant: 64).isActive = true
}

But I get the error:

'NSLayoutConstraint' is not convertible to 'Bool'

What's the best way to set the height for the view the label is in to a minimum height?

var myLabel: UILabel(){
   let label = UILabel()
   label.translatesAutoresizingMaskIntoConstraints = false
   label.textColor = UIColor.white
   label.font = UIFont(name: "Helvetica-Regular", size: 19)
   label.numberOfLines = 0
   label.sizeToFit()
   label.textAlignment = .center
   return label
}

let myView:UIView = {
   let view = UIView()
   view.translatesAutoresizingMaskIntoConstraints = false
   return view
}()

override func viewWillAppear(_ animated: Bool)
   super.viewWillAppear(animated){

   setViewAndLabel(dynamicText: //some text will get set here)
}

func setViewAndLabel(dynamicText: String){
   view.addSubView(myView)
   myView.backgroundColor = UIColor.red
   myView.topAnchor.constraint(equalTo: view.topAnchor, constant: 64).isActive = true
   View.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true

   myView.addSubView(myLabel)
   myLabel.text = dynamicText
   myLabel.topAnchor.constraint(equalTo: myView.topAnchor, constant: 0).isActive = true
   myLabel.widthAnchor.constraint(equalTo: myView.widthAnchor, constant: 0).isActive = true
   myView.bottomAnchor.constraint(equalTo: myLabel.bottomAnchor, constant: 0).isActive = true

   //this if statement doesn't work
   if myView.heightAnchor.constraint(lessThanOrEqualToConstant: 64){
        viewForErrorLabel.heightAnchor.constraint(equalToConstant: 64).isActive = true
   }
}
1 Answers
Related