Home > OS >  UIView fixed frame
UIView fixed frame

Time:03-13

I made a customView and I want the size of that view to be fixed.
Like UISwitch in which you can't even change the height and width value.
Or like UILabel. I want to add the view to storyboard without adding any height or width constraint with no missing constraint error.
I already override intrinsicContentSize but I still get the missing constraint error.
Is there any way to make height and width of a view constant that don't even get values?

CodePudding user response:

Simple solution

You can override the intrinsicContentSize variable and return the fixed size of your view.

So something like this should work in your custom view class:

override var intrinsicContentSize: CGSize {
    return CGSize(width: <Your width>, height: <Your height>)
}

More Advanced

Adding the intrinsicContentSize will work, but if a user adds a height constraint it can make the view confused or change the height of the view to match the constraint. If you Know the height of your custom view shouldn't change then you can manually change the height constraints from your view.

override func updateConstraints() {
    super.updateConstraints()
        
    if let constraint = self.constraints.first(where: { constraint in
        return constraint.isActive && constraint.firstAttribute == .height
    }) {
       constraint.constant = <Height of View>
    }
}

Ideally though, your best not adding this, but I'm just adding this here so it's an option if anyone needs it.

  • Related