2012-02-11 40 views
-2

方法声明的一个新实例,方法不返回一个UILabel

-(UILabel *)returnUILabel:(UILabel *)myLabel color:(UIColor *)labelColor x:(int)xParameter  y:(int)yParamater width:(int)widthParameter height:(int)heightParameter 
{ 
    CGRect cellFrame = CGRectMake(xParameter, yParamater, widthParameter, heightParameter); 
    myLabel = [myLabel initWithFrame:cellFrame]; 
    myLabel.text = @"Testing"; 
    myLabel.shadowOffset = CGSizeMake(1,1); 
    myLabel.backgroundColor = labelColor; 
    return myLabel; 
} 

称为低于viewDidLoad中,

UILabel *myLabel = [[UILabel alloc] init]; 
UIColor *labelColor = [UIColor redColor]; 

[self.view addSubview:[self returnUILabel:myLabel color:labelColor x:17 y:260 width:140 height:130]]; 
labelColor = [UIColor yellowColor] ; 
[self.view addSubview:[self returnUILabel:myLabel color:labelColor x:170 y:260 width:140 height:130]]; 
[super viewDidLoad]; 

在我看来,我只看到黄颜色的标签,而我应该可以看到一个红色和一个黄色。为什么? 同样的方法在UIImageView上正常工作。

感谢

回答

1

你只有一个UILabel,你却修改标签,而不是创建标签

- (UILabel *)returnUILabelWithColor:(UIColor *)labelColor x:(int)xParameter y:(int)yParamater width:(int)widthParameter height:(int)heightParameter 
{ 
    CGRect cellFrame = CGRectMake(xParameter, yParamater, widthParameter, heightParameter); 
    UILabel* newLabel = [[[UILabel alloc] initWithFrame:cellFrame] autorelease]; 
    newLabel.text = @"Testing"; 
    newLabel.shadowOffset = CGSizeMake(1,1); 
    newLabel.backgroundColor = labelColor; 
    return newLabel; 
} 
+0

为了清楚起见,您也可以从方法参数中删除'myLabel'。 – Costique 2012-02-11 19:07:55

+0

好抓!我刚从上面复制了这个方法。谢谢 – 2012-02-11 19:08:44

+0

是的,我知道我有一个标签,这就是我需要的。传递的参数在每种情况下都不相同,所以目前我可以在屏幕上看到添加到不同向量中的两个标签。如果你说的是正确的,为什么这种方法在UIIMageView上工作?为什么我低调? – 2012-02-11 19:10:40

1

问题在于这样一个事实,你现在只有一个UILabel对象和要添加它作为一个子视图的两倍。这不会制作标签的副本。

UIView reference

视图只能有一个上海华。如果视图已经有一个超级视图,并且该视图不是接收者,则在使接收者成为新的超级视图之前,此方法将删除先前的超级视图。

作为一个推论,如果superview是相同的,添加一个已经添加的子视图将简单地把它放在所有其他视图之上。

+0

但在二去我与不同的颜色发送标签的新实例,所以我应该得到一个红色和黄色的标签。就像我说的那样,这个方法在UIImageView上工作的很好。谢谢 – 2012-02-11 19:04:37

+0

试试这个:'[self.view addSubview:[self returnUILabel:[myLabel copy] color:labelColor x:170 y:260 width:140 height:130]];'。如果你想在屏幕上有两个对象,你肯定需要第二个对象。没有别的办法,对不起。 – sergio 2012-02-11 19:08:39