Search code examples
iosobjective-cswiftviewdidlayoutsubviews

getting highly confused by odd behaviour of viewController Method


I have overrided a method as

override func viewDidLayoutSubviews() {

    // creating bottom line for textField
        let border = CALayer()
        let width = CGFloat(1.0)
        border.borderColor = UIColor.whiteColor().CGColor
        border.frame = CGRect(x: 0, y: emailTextField.frame.size.height - width, width:  emailTextField.frame.size.width, height: emailTextField.frame.size.height)

        border.borderWidth = width
        emailTextField.layer.addSublayer(border)
        emailTextField.layer.masksToBounds = true

}

Now whats happening is that when I run my app on Iphone 6, 6+ every thing works fine. But when I run the same code on iphone5 (Simulator + real Device ) viewDidLayoutSubViews is getting called infinite times and my app becoms unresponsive. I solved the problem by using a bool variable. But I do not understand why is this happening. So can someone please explain this to me.

Thanks :-)


Solution

  • As docs says that viewDidLayoutSubviews method need for change layout

    Called to notify the view controller that its view has just laid out its subviews. 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. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout.

    Move your code to viewDidLoad method or to loadView if you are not using xibs or Storyboards

    override func viewDidLoad() {
    
        // creating bottom line for textField
            let border = CALayer()
            let width = CGFloat(1.0)
            border.borderColor = UIColor.whiteColor().CGColor
            border.frame = CGRect(x: 0, y: emailTextField.frame.size.height - width, width:  emailTextField.frame.size.width, height: emailTextField.frame.size.height)
    
            border.borderWidth = width
            emailTextField.layer.addSublayer(border)
            emailTextField.layer.masksToBounds = true
    
    }
    

    If you would like to change border.frame you can set it to class variable and change it in viewDidLayoutSubviews method

    override func viewDidLayoutSubviews() {
          self.border.frame = CGRect(x: 0, y: emailTextField.frame.size.height - width, width:  emailTextField.frame.size.width, height: emailTextField.frame.size.height)
          self.border.borderWidth = width    
    }