0

Suppose I have created a subclass of UIView to make a custom UI component and I have another view inside my custom view. Here's the code

class CustomView : UIVIew{
    private var innerView : UIView!

    convenience init(){
        self.init(frame : CGRectZero);
    }
    override init(frame : CGRect) {
        super.init(frame : frame);

        self.innerView = UIView();

        /*
          * The following code is the frame I want to set
            for my innerView evertimes iOS layouts my CustomView
            by means of NSLayoutConstraint because writing 
            NSLayoutConstraint programmatically is time consuming.

          * The Question is where to put this code ?
            Inside layoutIfNeeded() or layoutSubviews
        */
        let myDesiredWidth = self.frame.size.width * 0.8;
        let myDesiredHeight = self.frame.size.height * 0.8;
        let myDesiredX : CGFloat = (self.frame.size.width - myDesireWidth) / 2
        let myDesiredY : CGFloat = (self.frame.size.height - myDesireHeight) / 2;
        let myDesireFrame : CGRect = CGRectMake(myDesiredX, myDesiredY, myDesiredWidth, myDesiredHeight);

        self.innerView.frame = myDesireFrame;
    }

    override func layoutSubviews(){

    }
    override func layoutIfNeeded(){

    }

}

Inside my code, u can see there is innerView of type UIView as a private property. There is the frame for that view I want to set everytime iOS updates my CustomView's frame if someone or I add NSLayoutConstraint in my CustomView instance. When iOS updates the UIViewController's subviews by means of NSLayoutConstraint, which one is called, layoutIfNeeded() or layoutSubviews()? Swift or Objective-C , it doesnt matter.

Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75
  • `layoutIfNeeded()` will call `layoutSubviews()` if it determines that a layout pass is necessary. You should override `layoutSubviews()` – dan Sep 04 '16 at 03:37
  • You will get some idea from here http://stackoverflow.com/questions/1182945/how-is-layoutifneeded-used – Janmenjaya Sep 04 '16 at 03:53

0 Answers0