ios - 在哪里设置 subview 的图层属性?为什么不在 initWithCoder 中

标签 ios objective-c uiview uitableview custom-controls

我创建了一个自定义的 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

我遇到的问题是没有绘制这些图层属性。如果我在 awakeFromNibdrawRect 中调用 -initView 调用,它会按预期绘制。我的问题:为什么我的原始代码不起作用?我应该在哪里调用 initView?是否有一些 View 生命周期?我知道 initWithCoder 没有连接 socket ,但它没有在运行时崩溃。

我通读了Apple documentation around Views并在没有找到答案的情况下搜索 SO 问题。我找到了这个 SO answer , 但同样没有解释。

最佳答案

嘿,我找到了一个更好的方法,只需为您的 subview 添加一些运行时属性 cardContainer

像这样enter image description here

.m 文件中不再有代码。

编辑:

发件人: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).

关于ios - 在哪里设置 subview 的图层属性?为什么不在 initWithCoder 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626203/

相关文章:

ios - uitableViewCell.rounded Corners 不会立即显示

ios - 如何在 Xamarin 中处理 iOS 生物识别身份验证中的错误情况?

ios - 如何使用 MKRoute 创建特定路径?

ios - 如何从 UIScrollView 中查找和替换 subview

ios - 使用 CAShapeLayer() 为 UIView 创建 mask 层

iphone - FMOD 和简单的 If 语句

ios - 来自变量的 ViewController Storyboard ID

ios - 如何在用户不点击通知警报时获取通知数据只需使用 obj c 在 ios 中单击应用程序

ios - 从子类 setDelegate 设置父类(super class)委托(delegate)

ios - 在方向更改时自动缩放 UIView 以按比例缩放以适合父 View