gpt4 book ai didi

iphone - UIView drawRect 与 initWithFrame

转载 作者:行者123 更新时间:2023-12-03 20:22:29 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com