Where do you set a subview's layer properties? Why not in the initWithCoder

做~自己de王妃 提交于 2019-12-08 10:46:55

问题


I created a custom UITableViewCell (for this example, let's just say the subclass is MyViewCell) which has an Nib file associated to it MyViewCell.xib. The nib contains a UITableViewCell with one subview UIView (named cardContainer) that's simply a rectangle with a blue background. I want to add a drop shadow around the UIView, so I added set the layer properties in the -initWithCoder call:

@implementation MyViewCell


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initView];
    }
    return self;
}


- (void) initView
{
    UIBezier Path*shadowPath =[UIBezierPath bezierPathWithRect:view.bounds];        
    [self.cardContainer.layer setShadowColor: [UIColor blackColor].CGColor];
    [self.cardContainer.layer setShadowOpacity: 0.8];
    [self.cardContainer.layer setShadowRadius:3.0];
    [self.cardContainer.layer setShadowOffset: CGSizeMake(2.0,2.0)];
    view.layer.shadowPath = shadowPath.CGPath;
}


@end

The problem I'm having is that these layer properties aren't being drawn. If I call the -initView call within awakeFromNib or drawRect it's drawn as expected. My question: why doesn't my original code work? Where should I be calling initView? Is there some view lifecycle? I understand that the initWithCoder doesn't have the outlets connected, but it didn't crash at runtime.

I read through Apple documentation around Views and searched through the SO questions without finding an answer. I found this SO answer, but again doesn't explain.


回答1:


Hey I found a better way to do this ,just add some runtime attributes for your subview cardContainer

like this

no more code in .m file anymore.

EDIT:

From:NSNibAwaking Protocol

Important: Because the order in which objects are instantiated from an archive is not guaranteed, your initialization methods should not send messages to other objects in the hierarchy. Messages to other objects can be sent safely from within awakeFromNib—by which time it’s assured that all the objects are unarchived and initialized (though not necessarily awakened, of course).




回答2:


You need to add this,

self.cardContainer.layer.masksToBounds = NO;


来源:https://stackoverflow.com/questions/20626203/where-do-you-set-a-subviews-layer-properties-why-not-in-the-initwithcoder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!