iphone - UIView drawRect 与 initWithFrame

标签 iphone cocoa-touch uiview

我有一个 UIView,其中添加了几个作为 subview 的按钮。目前我的按钮位于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];
}

最佳答案

@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;
}

关于iphone - UIView drawRect 与 initWithFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3367685/

相关文章:

iphone - reloadData 到底调用了什么?

iphone - 在 Interface Builder 中连接 iOS socket

iphone - 使用 NSUserDefaults 保存游戏设置/状态的优点?

ios - 将参数传递给 addTarget :action:forControlEvents

objective-c - 警告 "Use of GNU statement expression extension"

objective-c - 用于应用程序数据更新的 iOS 设计模式

ios - NSPredicate 查找具有相同标签形式的 UIView self.view.subviews Swift

iphone - 加快 iPhone 3G 上的全屏图像绘制

ios - 如何在 **spriteKit** 中添加 UIView?

ios - 是否可以跟踪 UIView 框架的更改?