2010-07-29 80 views
2

我有一個UIView,它有幾個按鈕作爲子視圖添加到它。目前我在drawRect中有按鈕,我聽說這是一個壞主意,因爲可以多次調用drawRect。我試圖將這些UIButtons移動到initWithFrame,但它們不會被繪製。我應該如何解決這個問題?UIView drawRect vs 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]; 
} 
+1

OK,那麼你可以分享你的initWithFrame:方法的代碼?是initWithFrame:叫? – tonklon 2010-07-30 21:24:26

+0

添加了代碼。我不認爲這是有用的,雖然 – 2010-07-31 00:16:38

+0

此代碼不顯示任何按鈕被創建或添加到視圖。您可以將代碼發佈到您嘗試將它們添加到-initWithFrame中的視圖中嗎? – 2010-07-31 13:12:59

回答

7

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

+1這是更好的原因。 – tonklon 2010-07-30 21:23:36

2

一個爲textLabel我敢打賭,視圖是從筆尖文件加載?只要使用相同的代碼來添加子視圖中的initWithCoder:

UIView類參考:

如果您使用Interface Builder來設計 你的接口,這種方法並不 調用時您的視圖對象 隨後從nib文件加載。在筆尖文件 對象是 重構,然後使用它們的initWithCoder初始化 :方法,其中 修改 視圖的屬性來匹配存儲在 筆尖文件的屬性。有關如何從nib 文件加載視圖的詳細信息 ,請參見「資源編程指南」。

+1

對不起,這個房子沒有界面的建設者! – 2010-07-30 16:43:37