【问题标题】:Method does not return a new instance of a UILabel方法不返回 UILabel 的新实例
【发布时间】:2012-02-11 18:56:29
【问题描述】:

方法声明,

-(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

谢谢

【问题讨论】:

    标签: objective-c uilabel


    【解决方案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;
    }
    

    【讨论】:

    • 为了清楚起见,您还可以从方法参数中删除 myLabel
    • 好收获!我只是从上面复制了方法。谢谢
    • 是的,我知道我有一个标签,这就是我所需要的。每种情况下传递的参数都不同,因此目前我可以在屏幕上看到两个标签添加到不同的向量中。如果您所说的是正确的,为什么这种方法适用于 UIIMageView ?为什么我被否决了??
    • @XSlash 您的方法有效并且更干净,尽管我仍然必须了解为什么以前的方法适用于 UIIMageview。谢谢。
    • 我不能肯定回答,因为我看不出你是如何用你的 UIImageView 做的。但是,我建议您更改它,即使它现在可以工作,这也不是一个好方法。如果您不使用 ARC,那么您正在泄漏内存。我不知道你为什么被否决
    【解决方案2】:

    问题在于您只有 一个 UILabel 对象,并且您将其作为子视图添加了两次。这不会复制标签。

    来自UIView reference

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

    作为推论,如果父视图相同,添加已添加的子视图只会将其置于所有其他视图之上。

    【讨论】:

    • 但在第二次发送时,我发送了不同颜色的标签,所以我应该得到一个带有红色和黄色的标签。就像我说的那样,该方法在 UIImageView 上运行良好。谢谢
    • 试试这个:[self.view addSubview:[self returnUILabel:[myLabel copy] color:labelColor x:170 y:260 width:140 height:130]];。如果你想在屏幕上有两个对象,你肯定需要第二个对象。没有别的办法,抱歉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2015-05-23
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多