UIView drawRect和initWithFrame [英] UIView drawRect vs initWithFrame
问题描述
我有一个UIView有几个按钮添加到它作为子视图。目前我有drawRect:中的按钮,我听说是一个坏主意,因为drawRect可以调用几次。我试图将这些UIButtons移动到initWithFrame,但他们只是不绘制。我应该如何解决这个问题?
I have a UIView which has several buttons added to it as subviews. Currently I have the buttons in drawRect:, which I have heard is a bad idea because drawRect can be called several times. I tried to move these UIButtons to initWithFrame, but they just don't get drawn. How should I fix this?
我没有使用界面生成器,所以没有NIB文件存在。调用initWithFrame。我通过添加一个NSLog(...)检查,我的NSMutableArrays正在正确初始化。
I am not using interface builder, so there are no NIB files present. The initWithFrame is called. I checked by adding an NSLog(...), and my NSMutableArrays are being properly initialized.
我的initWitFrame:代码目前有很少。
My initWitFrame: code currently has very little. It is
- (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;
}
我试图添加一个textlabel,如下所示
I have tried to add a textlabel like the following
#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
initializer:
@tonklon is spot on. Additionally, the usual pattern is to have your custom initialization code in a third method, such as -sharedInit
, which is called after the appropriate super
initializer:
- (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;
}
这篇关于UIView drawRect和initWithFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!