iphone - UIScrollView 内部分透明内容的奇怪行为

标签 iphone ios scroll drawing transparent

我的观点的实现如下。 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/

相关文章:

javascript - 如何设置水平滚动位置 react

ios - 直接向iOS接收推送通知(未与应用程序链接)

iphone - -当不使用xib时,内存警告后不调用viewDidUnload

ios - 如何访问 cocoa pod 库并向其添加模块?

iphone - NSMutableURLRequest 偶尔出现 "no boundary"错误

ios - 根据选择自动向下滚动

iphone - NSTimer失效后后台线程NSRunloop运行不退出!为什么?

iphone - 将 int 类型的变量传递给parentViewController [iOS]

ios - 所有 iOS .p12 证书都需要密码吗?

Android:可滚动(水平和垂直)的带有按钮覆盖的 ImageView