關於layoutIfNeeded


對於layoutIfNeeded本人淺談下自己的理解,首先我們要了解為何在用到用到constraint的動畫時以下代碼無法實現動畫的功能:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    [UIView animateWithDuration:2.0 animations:^{
      
       self.blueViewH.constant = 80;
    }];
}

而我們直接使用frame的時候動畫是可以實現的:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    [UIView animateWithDuration:2.0 animations:^{
        
        CGRect  size =self.blueView.frame;
        
        size.size.height = 80;
        
        self.blueView.frame = size;
        
    }];
}

說明,我們所調用的方法是正確的,那么我們可以大膽的假設"self.blueViewH.constant = 80;"在這句賦值並沒有在該方法中完成,從而導致動畫並沒有實現;而要進行Constraint動畫則需要對NSLayoutConstraint的對象賦值之后調用layoutIfNeeded方法才能實現動畫(由於Xcode改版后調用layoutIfNeeded方法只會刷新子控件鍵,因此要使用必須通過它的父類):

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    self.blueViewW.constant = 80;
    
    [UIView animateWithDuration:2.0 animations:^{
  
        [self.view layoutIfNeeded];
    }];
}

通過兩個能夠實現動畫的代碼比較,我們就可以推測出NSLayoutConstraint的本質就是在系統底層轉換為frame,並且NSLayoutConstraint的轉換還不是在你賦值的時候就轉換完成,而是極可能在某一方法結束后才進行轉換;因此我們調用layoutIfNeeded方法對"self.blueViewW.constant = 80;"代碼進行強制刷新的時候便能實現該動畫了.

總之,layoutIfNeeded在需要重新布局的時候立即刷新進行重新布局,不受其他因素影響.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM