2013-09-25 49 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