Dynamic height of UIView as per device dimensions

Gagan Vishal Mishra
2 min readMar 7, 2022

--

in some cases, we want the view must be of dynamic height as per device height. In order to provide this feature, we can create a subclass of UIView as below

import UIKitclass CommonCardHeaderView: UIView {

override init(frame: CGRect) {
super.init(frame: frame)
resetViewHeight()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
resetViewHeight()
}
// MARK:- Reset Height as per device size
func resetViewHeight(){
// Here suppose we have a background image for added view. In that case we can calulate value of multiplier from image height/widhth
let image = UIImage(named: "backgound_image")!
let multiplier : CGFloat = image.size.height/image.size.width
// in Case there is no background image, then we can add custom constant value say 145/320. Here 320 pxl is width of iPhone 5/5S.
// let multiplier : CGFloat = 145/320

self.heightAnchor.constraint(equalTo: self.widthAnchor, multiplier: multiplier, constant: 0).isActive = true
}
}

Suppose that you are using a storyboard then add a UIView which you want to make dynamic height and replace the class name with CommonCardHeaderView (Screenshot)

That's it in Storyboard. Dynamic UI is ready.

In case you are creating UI via code then simply create an instance of CommonCardHeaderView instead of UIView.

Enjoy!!!

--

--

Gagan Vishal Mishra

Experienced Sr iOS and mobile app developer. Love to solve customer problem in the easiest and quickest way.