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

Uiview iOS:将字符串值传递给其他XIB的UILabel,uiview,ios7,xib,Uiview,Ios7,Xib,//提供的更新 我有一个故事板UIViewController应用程序。 我还有其他的XIB(继承自UIView,上面只有一个标签),如下所示 以下是Main.storyboard的内容(MyController是扩展UIViewController的接口) 以下是MySquare.xib的内容(MySquare是扩展UIView的接口) 现在,我必须创建MySquare实例的3个ui视图,并将其添加到MyHolderView中 我试图为这3个UIView的标签文本指定新标签。 但我无法看到新标

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

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

以下是MySquare.xib的内容(MySquare是扩展UIView的接口)

现在,我必须创建MySquare实例的3个ui视图,并将其添加到MyHolderView中

我试图为这3个UIView的标签文本指定新标签。 但我无法看到新标签,但只有默认标签出现

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

更新 我已经像这样重写了MySquare的init方法。还是不走运。 我在初始化MySquare视图的UIViewController中调用以下方法。 从UIViewController调用:

        MySquare *square=[[MySquare alloc]initWithFrame:CGRectMake(20,20,50,50) string:[[NSString alloc] initWithFormat:@"%d",myVar]];
重写初始化函数的实现

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

}您需要理解类和实例之间的区别。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
)的引用作为实例变量。

这可能有助于您阅读我的书中关于实例如何产生的章节:嗨,实际上我尝试过类似的方法。此外,我没有连接IBOutlet。你的建议奏效了!谢谢!:)
    [self addSubview:[[[NSBundle mainBundle] 
         loadNibNamed:@"View" owner:self options:nil] objectAtIndex:0]];
    [self.myLabel setText:[[NSString alloc]initWithString:str]];
    MySquare* square = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:nil] objectAtIndex:0]];
    [self addSubview:square];
    [square.myLabel setText:@"Look, it is working!"];