Reputation: 445
I have a custom view and xib. I use this custom view in one of my storyboard's controller views.
I have a use case where I want to be able to hide the custom view (and bring its height to zero). Right now, I set the height in the interface builder and set constraints to the superview's edges:
As you can see, I want its height to be 84
everywhere.
Now here is my custom view's class:
import UIKit
@IBDesignable
class BannerView: UIView {
@IBOutlet var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override func awakeFromNib() {
super.awakeFromNib()
initialize()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
initialize()
contentView?.prepareForInterfaceBuilder()
}
func initialize() {
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "BannerView", bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
func hide() {
// Hide the view and set its height to zero here
}
}
But, now I'm confused... should I also be setting a height constraint on the custom view when I load it into one of my storyboards? Or should its height be 84
everywhere and I shouldn't have to specify it any further?
Also, how would I hide the custom view and set its height to zero in the above hide()
function?
Upvotes: 1
Views: 767
Reputation: 77452
There are several ways to do this... here's one.
Give the content of your xib constraints to make its height 84-pts. You haven't shown your xib's layout, but I'll assume you know how to do that.
Then, when you add BannerView
to your main view (I'm guessing that's what you're doing), embed it in a Vertical UIStackView
with these properties:
Now, when you set bannerView.isHidden = true
, the stack view automatically removes it from the height calculations, resulting in the stack view having a height of Zero.
Setting bannerView.isHidden = false
will then re-display the banner view along with its height.
Upvotes: 1
Reputation: 79
As you want the view's height to be 84 everywhere I think you should add a height constraint outlet and set the value 84. Set the constraint value to 0 to hide the view (I highly suggest not to hide some view by doing this).
Upvotes: 0