Mike Jenkins Mike Jenkins - 3 months ago 46
Swift Question

AutoLayout resize custom UIView content

I have a standard UIView added via IB which changes size based on orientation using constraints. Programatically I add a custom component (sub-classing UIView) to this view which by default is the sam size as its parent view. Problem is, how do I get my custom view (programatically added) to update its size based to match its parent when the parents size changes (due to orientation change)?

@IBOutlet weak var cardView: UIView!
override func viewDidLoad() {
super.viewDidLoad()

let frame = cardView.bounds
// Custom component sub classes UI View
// Should always be same size as its parent
let imageTemplateView: ImageTemplateView = ImageTemplateView(frame: frame)

cardView.addSubview(imageTemplateView)
}

Answer

Here comes viewDidLayoutSubviewsto resolve our issue,

Description:

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method.

Instead of viewDidLoad use viewDidLayoutSubviewsas follows

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let imageTemplateView: ImageTemplateView = ImageTemplateView(frame: frame)
    cardView.addSubview(imageTemplateView)
    imageTemplateView.clipsToBounds = true
}

UPDATE:

  • Declare variable above viewdidload

    var imageTemplateView: ImageTemplateView = ImageTemplateView()
    
  • set frame and add it as sub view in viewdidload

    override func viewDidLoad() {
      imageTemplateView = ImageTemplateView(frame: frame)
      cardView.addSubview(imageTemplateView)
      imageTemplateView.clipsToBounds = true
    }
    
  • In viewDidLayoutSubviews just set the frame alone,so that whenever orientation changes ImageTemplateView's frame will be updated

    override func viewDidLayoutSubviews() {
      super.viewDidLayoutSubviews()
      imageTemplateView = ImageTemplateView(frame: frame)
    }
    
Comments