【问题标题】:UIView drawRect vs initWithFrameUIView drawRect 与 initWithFrame
【发布时间】:2010-07-29 23:12:15
【问题描述】:

我有一个 UIView,其中添加了几个按钮作为子视图。目前我在 drawRect: 中有按钮,我听说这是一个坏主意,因为 drawRect 可以被多次调用。我试图将这些 UIButtons 移动到 initWithFrame,但它们只是没有被绘制。我应该如何解决这个问题?

我没有使用界面生成器,因此不存在 NIB 文件。调用 initWithFrame。我通过添加 NSLog(...) 进行了检查,并且我的 NSMutableArrays 正在正确初始化。

我的 initWitFrame: 代码目前很少。这是

- (id)initWithFrame:(CGRect)frame 
{
    if (self = [super initWithFrame:frame]) 
    {
        results = [[NSMutableArray alloc] init];
        inputs = [[NSMutableArray alloc] init];
        format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"EEE, MMM dd, yyyy"];
        renc =[[RenameController alloc] init];
    }
    return self;
}

我尝试添加如下文本标签

#define BOX_WIDTH 155.0
#define BOX_OFFSET 45.00
#define ROW_HEIGHT 27

- (id)initWithFrame:(CGRect)frame 
{
    if (self = [super initWithFrame:frame]) 
    {
        results = [[NSMutableArray alloc] init];
        inputs = [[NSMutableArray alloc] init];
        format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"EEE, MMM dd, yyyy"];
        renc =[[RenameController alloc] init];

        double row=0.0;
        [self makelabel:@"Start" at:CGRectMake(0, row, BOX_OFFSET, ROW_HEIGHT)];
    }
    return self;
}

-(void) makelabel:(NSString *) str at:(CGRect) rect
{
    UILabel *title = [[UILabel alloc] initWithFrame:rect];
    title.text = str;
    title.textAlignment = UITextAlignmentLeft;
    title.textColor = [UIColor blackColor];
    title.backgroundColor = [UIColor clearColor];
    title.font = [UIFont boldSystemFontOfSize:FONT_SIZE];
    [self addSubview:title];
    [title release];
}

【问题讨论】:

  • 好的,那你可以分享你的initWithFrame:代码吗?是否调用了 initWithFrame:?
  • 添加了代码。我认为它没有那么有用
  • 此代码不显示任何正在创建或添加到视图的按钮。您能否发布您尝试将它们添加到 -initWithFrame: 中的视图的代码?

标签: iphone cocoa-touch uiview


【解决方案1】:

@tonklon 很到位。此外,通常的模式是将您的自定义初始化代码放在第三种方法中,例如 -sharedInit,它在适当的 super 初始化程序之后调用:

- (id)sharedInit {
    // do whatever, possibly releasing self on error and returning nil
    return self;
}

- (id)initWithFrame: (CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        self = [self sharedInit];
    }
    return self;
}

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

【讨论】:

    【解决方案2】:

    我敢打赌视图是从 nib 文件加载的?只需使用相同的代码在 initWithCoder 中添加您的子视图:

    UIView 类参考:

    如果你使用 Interface Builder 来设计 你的界面,这个方法不是 当您的视图对象被调用时 随后从 nib 文件加载。 nib 文件中的对象是 重组然后初始化 使用他们的 initWithCoder: 方法, 它修改了属性 视图以匹配存储在 笔尖文件。详细信息 关于如何从 nib 加载视图 文件,请参阅资源编程指南。

    【讨论】:

    • 对不起,这房子里没有界面生成器!
    猜你喜欢
    • 2017-10-24
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多