iOS:将字符串值传递给其他XIB的UILabel

时间:2014-02-02 14:34:28

标签: uiview ios7 xib

//提供更新 我有一个故事板UIViewController应用程序。 我有其他XIB(继承自UIView只有一个标签),如下所示

以下是内容Main.storyboard(MyController是扩展UIViewController的接口)

> ViewController         (UIViewController)
    > MyHolderView       (UIView)

以下是MySquare.xib的内容(MySquare是扩展UIView的界面)

> MySquare               (UIView)
    > MyLabel            (UILabel)  (Having Default value LABEL, entered in attribute inspector)

现在我必须制作3个UIViews实例MySquare并将其添加到MyHolderView

我尝试为这3个UIView的标签文本分配新标签。 但我无法看到新标签,只有默认标签LABEL即将到来。

MySquare *square=[[MySquare alloc]init]; 
//square.myLabel.text = @"TRY";
[square.myLabel setText:[[NSString alloc]initWithFormat:@"%d",(myVar)]];

请帮忙。

更新 我已经像我这样覆盖了我的MySquare的init方法。仍然没有运气。 我从UIViewController调用下面的方法,在那里我初始化我的MySquare视图。 从UIViewController调用:

        MySquare *square=[[MySquare alloc]initWithFrame:CGRectMake(20,20,50,50) string:[[NSString alloc] initWithFormat:@"%d",myVar]];

重写的init函数的实现

- (id)initWithFrame:(CGRect)frame string:(NSString *)str;
{
    self = [super initWithFrame:frame];
    if (self) {
        self.myLabel.text=@"A";
        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] objectAtIndex:0]];
        [self.myLabel setText:[[NSString alloc]initWithString:str]];
 }
return self;

}

1 个答案:

答案 0 :(得分:0)

您需要了解类和实例之间的区别。 MySquare是一个类,但您需要在界面中引用MySquare的实际实例。因此这段代码毫无意义:

MySquare *square=[[MySquare alloc]init]; 
[square.myLabel setText:[[NSString alloc]initWithFormat:@"%d",(myVar)]];

它运行正常,但问题是 MySquare实例您界面中的MySquare实例。 (它只是您创建的一个单独的MySquare实例,在您的代码中浮动。)因此,您无法看到发生的任何事情。

现在让我们考虑一下这段代码:

    [self addSubview:[[[NSBundle mainBundle] 
         loadNibNamed:@"View" owner:self options:nil] objectAtIndex:0]];
    [self.myLabel setText:[[NSString alloc]initWithString:str]];

在这里,您确实从nib中获取了一个MySquare实例并将其放入您的界面中。好。但你没有任何参考,所以你没有(简单)的方式与它交谈!特别是,self.myLabel与MySquare实例的myLabel不同。

你离开了一步!您需要对MySquare实例的引用,如下所示:

    MySquare* square = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] objectAtIndex:0]];
    [self addSubview:square];
    [square.myLabel setText:@"Look, it is working!"];

即使这样还不够,如果您希望将来与square.myLabel 交谈。您需要保持square(或square.myLabel)的引用作为实例变量。