2013-09-25 43 views
1

我有一堆UILabels需要全部設置相同,但具有不同的幀。由於有很多人,我想我會通過使一個函數來做到這降低了代碼量:通過函數初始化一個實例變量

-(void)addField:(UILabel *)label withFrame:(CGRect)frame toView:(id)view { 
    label = [[UILabel alloc] initWithFrame:frame]; 
    label.layer.cornerRadius = 3; 
    [view addSubview:label]; 
} 

,並通過調用它:

[self addField:fieldOneLabel withFrame:CGRectMake(20, 180, 61, 53) toView:theView]; 

這個工程到一個點的字段顯示正確,但查看它fieldOneLabel不初始化,所以它只是一個不再被引用的UILabel那裏。我想我可能不得不使用&,但我想我的理解是不正確的,因爲它會導致編譯器錯誤。我該怎麼做?

+0

你得到了什麼編譯器錯誤? –

+0

將非本地對象的地址傳遞給__autoreleasing參數用於回寫 – Rudiger

回答

0

我改成了不發送的UILabel向功能,但返回創建的標籤:

-(UILabel *)addFieldWithFrame:(CGRect)frame toView:(id)view { 
    UILabel *label = [[UILabel alloc] initWithFrame:frame]; 
    label.layer.cornerRadius = 3; 
    [view addSubview:label]; 
    return label; 
} 

並通過調用:

fieldOneLabel = [self addFieldWithFrame:CGRectMake(self.view.bounds.size.width/2 - 128, 13, 61, 53) toView:view]; 

雖然與Sco類似答案我想避免在另一行添加視圖。

3

您可能要返回標籤,然後將其添加到UIView的更多是這樣的:

-(UILabel*)createLabelWithText:(NSString*)text andFrame:(CGRect)frame { 
    UILabel *label = [[UILabel alloc] initWithFrame:frame]; 
    [label setText:text]; 
    label.layer.cornerRadius = 3; 
    return label; 
} 

然後在你的代碼,你可以做到以下幾點:

UILabel *xLabel = [self createLabelWithText:@"Some Text" andFrame:CGRectMake(20, 180, 61, 53)]; 
[theView addSubview:xLabel]; 

,或者如果你想訪問它後來作爲一個屬性:

self.xLabel = [self createLabelWithText:@"Some Text" andFrame:CGRectMake(20, 180, 61, 53)]; 
[theView addSubview:xLabel]; 
+0

我將從addFieldWithFrame中重命名該方法,因爲它不再將該字段添加到視圖中。更好的解決方案是使用方法+ labelWithFrame:(CGRect)框架爲UILabel創建一個類別。 –

+0

我很高興能使用它,但是有可能按照我目前的方式進行操作嗎? – Rudiger

1
-(void)addField:(UILabel * __autoreleasing *)fieldOneLabel withFrame:(CGRect)frame toView:(id)view { 
    if (fieldOneLabel != nil) { 
     *fieldOneLabel = [[UILabel alloc] initWithFrame:frame]; 
     (*fieldOneLabel).layer.cornerRadius = 3; 
     [view addSubview:(*fieldOneLabel)]; 
    } 
} 

,並通過調用它:

[self addField:&fieldOneLabel withFrame:CGRectMake(20, 180, 61, 53) toView:theView]; 

使用__autoreleasing可避免電弧內存問題

+0

我已經非常接近這個,但它給錯誤傳遞非本地對象的地址爲__autoreleasing參數回寫。有什麼想法嗎? – Rudiger

+0

我有一種感覺,這是不可能在ARC了? – Rudiger

+0

使用啓用弧的xcode5構建時沒有生成錯誤或分析錯誤,所以我認爲沒有弧問題 – lanbo