【问题标题】:Add a subclass of subview to a subclass of UIView将子视图的子类添加到 UIView 的子类中
【发布时间】:2013-01-02 14:56:23
【问题描述】:

我正在尝试做一些非常基本的事情。我想向我的 UIView 子类添加一个子视图。我假设我会将它放在下面的 initWithFrame 方法中,但是作为此类实例的视图不会绘制此子视图。我究竟做错了什么?

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        redView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
        [redView setBackgroundColor:[UIColor redColor]];
        [self addSubview:redView];
    }

    return self;
}

BTW redView 是定义在子类头部的一个属性,比如:

@property (strong, nonatomic) UIView *redView;

感谢阅读!

【问题讨论】:

  • 代码看起来不错。尝试将 self.backgroundColor 设置为绿色以查看它是否显示。
  • 实际上 initWithFrame 不会触发。我正在将情节提要中的元素分配给这个子类...
  • 你如何分配初始化那个视图?

标签: ios objective-c uiview


【解决方案1】:

你应该把你的初始化代码放在里面:

- (id)initWithCoder:(NSCoder *)aDecoder { ... }

或

- (void)awakeFromNib { ... }

当从 nib 加载视图时会调用这些方法。不要忘记在上述方法中调用[super ...]。

【讨论】:

  • 这只是部分答案;它碰巧起作用了,因为 OP 显然正在使用 NIB。更正确的答案是在从 initWithCoder 和 initWithFrame 调用的方法中执行初始化;这将涵盖程序加载和 NIB 加载。
猜你喜欢
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多