话不多说,先贴代码
- (IBAction)showView:(id)sender {
UIView * v = [[UIView alloc] initWithFrame:self.view.bounds];
UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)];
[v addGestureRecognizer:tapGes];
v.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
[[UIApplication sharedApplication].keyWindow addSubview:v];
self.bgView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 120, 300, 0)];
//设置autoresizesSubviews为 NO,避免 bgView 改变 bounds 时,对子视图进行重新布局
self.bgView.autoresizesSubviews = NO;
_bgView.backgroundColor = [UIColor redColor];
for (int i = 0; i < 2; i++) {
MyView * v = (MyView *)[[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil] lastObject];
v.frame = CGRectMake(0, i * 30, 200, 40);
v.backgroundColor = [UIColor greenColor];
[_bgView addSubview:v];
}
[v addSubview:_bgView];
[UIView animateWithDuration:2 animations:^{
_bgView.frame = CGRectMake(20, 120, 300, 150);
} completion:^(BOOL finished) {
NSLog(@"%@", _bgView.subviews);
}];
}
这段代码主要实现的功能是点击一个按钮,弹出一个全屏的遮罩,遮罩上有一个 Scrollview(在这里是 bgView),scrollview 里有几个子视图,在遮罩出现的时候, scrollview 要有一个高度从0变到某个值的动画.
在未写下面这句代码的时候,一直达不到效果
self.bgView.autoresizesSubviews = NO;
效果如下:
可以看出,子 view 的尺寸并不是代码设置的那样,那是因为他们的父 view, 也就是 bgView 的属性autoresizesSubviews默认为 YES.
该属性说明如下:
A Boolean value that determines whether the receiver automatically resizes its subviews when its bounds change.
When set to YES, the receiver adjusts the size of its subviews when its bounds change. The default value is YES
当为 YES 的时候,会在 frame 变化时调整子视图,造成未知的变化.
因此为了避免这种效果,应该设置该属性为 NO
最终想要的效果