我创建了一个自定义的 UITableViewCell
(对于这个例子,假设子类是 MyViewCell
),它有一个关联的 Nib 文件 MyViewCell.xib
。 nib 包含一个 UITableViewCell
和一个 subview UIView
(名为 cardContainer
),它只是一个蓝色背景的矩形。我想在 UIView
周围添加阴影,所以我在 -initWithCoder
调用中添加了设置图层属性:
@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
我遇到的问题是没有绘制这些图层属性。如果我在 awakeFromNib
或 drawRect
中调用 -initView
调用,它会按预期绘制。我的问题:为什么我的原始代码不起作用?我应该在哪里调用 initView
?是否有一些 View 生命周期?我知道 initWithCoder
没有连接 socket ,但它没有在运行时崩溃。
我通读了Apple documentation around Views并在没有找到答案的情况下搜索 SO 问题。我找到了这个 SO answer , 但同样没有解释。
最佳答案
嘿,我找到了一个更好的方法,只需为您的 subview 添加一些运行时属性 cardContainer
像这样
.m 文件中不再有代码。
编辑:
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).
关于ios - 在哪里设置 subview 的图层属性?为什么不在 initWithCoder 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626203/