我的观点的实现如下。 scrollView 是 UIScrollView 类型的 iVar。
“奇怪的行为”是,当我 ScrollView 时,背景逐渐从橙色变为绿色。看起来几乎透明的标签背景以某种方式自行堆叠,直到最终得到绿色背景。但我不明白为什么它会这样做。谁能解释一下吗?
#import "ViewWithScrollView.h"
@implementation ViewWithScrollView
@synthesize scrollView;
-(void) layoutSubviews {
scrollView.frame = self.bounds;
CGSize size = self.frame.size;
size.width*=2;
size.height*=2;
scrollView.contentSize = size;
scrollView.backgroundColor = [UIColor orangeColor];
// scrollView.clearsContextBeforeDrawing = YES; //These two lines can be commented in or out; it makes no difference.
// scrollView.opaque = NO;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0,0,size.width, size.height)];
label.textAlignment = UITextAlignmentCenter;
label.font = [UIFont systemFontOfSize:200];
label.text = @"Princess!";
label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor colorWithRed:0. green:1. blue:0. alpha:0.01];
// label.opaque = NO; // same for these two lines
// label.clearsContextBeforeDrawing = YES;
[scrollView addSubview: label];
}
- (id)initWithFrame: (CGRect) frame {
self = [super initWithFrame:frame];
if (self) {
// self.opaque = NO; //again, commenting these in or out makes no difference
// self.clearsContextBeforeDrawing = YES;
scrollView = [[UIScrollView alloc]init];
[self addSubview:scrollView];
}
return self;
}
@end
最佳答案
每次调用 -layoutSubviews
时,您都会创建一个新标签。这种情况发生的频率可能比您想象的要高,而且越来越多。
如果您的 View 中始终有一个标签,请继续将其设为实例变量。将标签的创建移至 View 的 -initWithFrame:
方法,与 ScrollView 一起。也将其添加为 subview 。
基本上,将您想要执行一次的操作(对象创建、层次结构)放入 -initWithFrame:
中,以及由于布局更改而可能需要重复执行的操作(大小、定位等) ) 到 -layoutSubviews
中。
关于iphone - UIScrollView 内部分透明内容的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4693661/