Where should I be setting autolayout constraints when creating views programmatically

后端 未结 8 716
不思量自难忘°
不思量自难忘° 2020-12-07 07:52

I see different examples where constraints are set. Some set them in viewDidLoad / loadView (after the subview was added). Others set them in the m

相关标签:
8条回答
  • 2020-12-07 08:36

    I have this solution to change constraints before those who are in the storyboard are loaded. This solution removes any lags after the view is loaded.

    -(void)updateViewConstraints{
    
        dispatch_async(dispatch_get_main_queue(), ^{
    
                //Modify here your Constraint -> Activate the new constraint and deactivate the old one
    
                self.yourContraintA.active = true;
                self.yourContraintB.active= false;
                //ecc..
               });
    
        [super updateViewConstraints]; // This must be the last thing that you do here -> if! ->Crash!
    }
    
    0 讨论(0)
  • 2020-12-07 08:39

    Following example is to pass any view to another class. create my view from storyboard

    Swift 5.0

        override func viewWillAppear(_ animated: Bool) {
            
          super.viewWillAppear(animated) 
            DispatchQueue.main.async {
                self.abcInstance = ABC(frame: self.myView.frame)
              } 
          }
    
     
    

    If you miss DispatchQueue.main.async , it will take time to update constraints in viewWillAppear. Create myView in storyboard and give constraints same as screen width & height , then try printing frame of myView. it will give accurate value in DispatchQueue.main.async or in viewDidAppear but not give accurate value in viewWillAppear without DispatchQueue.main.async.

    0 讨论(0)
提交回复
热议问题