2015-11-06 88 views
1

我有一個UIView子類並重寫layoutSubviews方法。 當我在我的viewController中調用這個子類,並將其添加到控制器視圖中時,我發現「layoutSubviews」函數已被調用兩次。爲什麼layoutSubviews調用兩次?

coverFlowView = CoverFlowView(frame: CGRectMake(0, 40, UIScreen.mainScreen().bounds.size.width, 480)) 
coverFlowView.delegate = self 
coverFlowView.dataSource = self 
self.view.addSubview(coverFlowView) 

CoverFlowView是UIView的

+0

這就是它的工作方式。我有一個控制器,這被稱爲五次。取決於控制器及其設置方式。編寫可以處理這種情況的代碼。 – dasdom

+0

沒有任何其他代碼,如更改框架或旋轉,只需addSubView.How我可以處理這種情況? – Eric

+0

以''layoutSubviews''的方式將代碼編寫成可以多次調用的方式。一般來說,儘量避免重寫'layoutSubviews'。 – dasdom

回答

0

我遇到同樣的疑難問題。嘗試了不同的操作系統和不同得到的結果相同代碼國旗的視圖子類:

一個設備只能撥打layoutSubViews一次,但一個又一個叫了兩聲造成一個錯誤我的代碼...

我的代碼:

CGFloat step = 0.0; 

    if (self.array_rateOfEachColor) { 

     CGFloat sumRate = 0.0; 
     for (NSString *rate in self.array_rateOfEachColor) { 

      sumRate +=[rate floatValue]; 

     } 

     NSAssert(sumRate != 1.0 , @" sum of all elemetns for array array_rateOfEachColor must be 1.0 "); 

     for (int i = 0 ; i < [self.mutableArray_layers count]; i ++) { 

      CGFloat step = [[_array_rateOfEachColor objectAtIndex:i] floatValue]; 

      CAShapeLayer *tmp = [self.mutableArray_layers objectAtIndex:i]; 

      [tmp setStrokeStart:self.strokeEndValue]; 

      if (i == (self.mutableArray_layers.count -1)) { //the last layer 

       self.strokeEndValue = 1.0 - self.space ; 
       [tmp setStrokeEnd:self.strokeEndValue]; 
      }else { 

       [tmp setStrokeEnd:self.strokeEndValue + step ]; 
      } 

      self.strokeEndValue += (step + self.space); // record last strokeEndValue 
     } 

    }else{ 

     step = 1.0/self.mutableArray_layers.count; //average step 

     for (int i = 0 ; i < [self.mutableArray_layers count]; i ++) { 

      CAShapeLayer *tmp = [self.mutableArray_layers objectAtIndex:i]; 

      [tmp setStrokeStart:self.strokeEndValue]; 

      if (i == (self.mutableArray_layers.count -1)) { //the last layer 

       self.strokeEndValue = 1.0 - self.space ; 
       [tmp setStrokeEnd:self.strokeEndValue]; 
      }else { 

       [tmp setStrokeEnd:self.strokeEndValue + step ]; 
      } 

      self.strokeEndValue += (step + self.space); // record last strokeEndValue 

     } 
    } 
    self.strokeEndValue = 0.0; // different os , the layoutSubViews was called different times,so,this line is resolve this problem so that figure can be shown correctly 
} 
相關問題