为什么layoutSubviews会调用两次?

时间:2015-11-06 10:11:00

标签: swift2 layoutsubviews

我有一个UCiew的subClass并覆盖layoutSubviews方法。 当我在viewController中调用这个subClass,并将其添加到控制器的视图中时,我发现“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

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。我尝试了不同的操作系统并获得了相同代码标志的不同结果:

一个设备只调用layoutSubViews一次,但另一个调用两次导致我的代码出现一个bug ...

我的代码:

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
}