简体   繁体   English

在UIView init中添加CALayer子图层

[英]Adding a CALayer sublayer inside of UIView init

I'm trying to add a CALayer as a sublayer in a UIView subclass, but when I add the sublayer inside the init method I get EXC_BAD_ACCESS when I add the view to another view or window. 我正在尝试将一个CALayer添加为UIView子类中的子层,但是当我在init方法中添加子层时,当我将视图添加到另一个视图或窗口时,我得到EXC_BAD_ACCESS

Init method: Init方法:

- (id)initWithTitle:(NSString *)title message:(NSString *)message
{
    if ((self = [super init]))
    {
        self.title = title;
        self.message = message;

        self.alertLayer = [[CALayer alloc] init];

        self.layer.cornerRadius = kCORNER_RADIUS;
        self.layer.shadowRadius = 3.0;
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOffset = CGSizeMake(15, 20);
        self.layer.shadowOpacity = 1.0;

        self.alertLayer.delegate = self;
        self.alertLayer.masksToBounds = YES;
        self.alertLayer.cornerRadius = kCORNER_RADIUS;

        [self.layer addSublayer:self.alertLayer]; // This line of code seems to cause EXC_BAD_ACCESS
    }

    return self;
}

EXC_BAD_ACCESS is caused after calling [self.view addSubview:alertView] inside a view controller or UIWindow. EXC_BAD_ACCESS正在呼叫后引起[self.view addSubview:alertView]视图控制器或一个UIWindow内部。

You have two layers ( self.layer and self.alertLayer ) which have the same delegate self , this leads to an infinite recursion in internal method -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:] when added this view ( self ) to the view tree. 你有两个层( self.layerself.alertLayer )具有相同的委托self ,这导致内部方法无限递归-[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:]添加此视图时( self )到视图树。 Therefore you must remove self.alertLayer.delegate = self; 因此,您必须删除self.alertLayer.delegate = self; to avoid crash. 避免崩溃。 If you need to delegate for alarmLayer you can create distinct object. 如果需要委派alarmLayer ,则可以创建不同的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM