Iphone 如何全局初始化目标C中的按钮?

Iphone 如何全局初始化目标C中的按钮?,iphone,objective-c,Iphone,Objective C,我用了两个按钮。我想从两个不同的函数访问这两个按钮对象- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization button1= [UIButton bu

我用了两个按钮。我想从两个不同的函数访问这两个按钮对象-

 (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
        button1= [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
        button2= [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
        button1.frame = CGRectMake(50, 50, 100, 30);
        button2.frame = CGRectMake(160, 50, 100, 30);
    }
    return self;
}
我的函数是foo()和bar()。 在这些函数中,我使用按钮1和按钮2。
但它不起作用。

首先,我建议使用Interface Builder创建按钮,并将它们连接到控制器中的IBOutlets。然后,您可以定义访问器方法,以允许您从控制器外部的函数/方法访问这些按钮(或使用
@synthesis
自动定义它们)。您需要小心不要太多地破坏封装。你到底想用你的函数做什么

编辑:正如我在下面的评论中提到的,我现在已经找出了问题所在。您需要保留按钮,如下所示:

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
        button1= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        button2= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        button1.frame = CGRectMake(50, 50, 100, 30);
        button2.frame = CGRectMake(160, 50, 100, 30);
    }
    return self;
}

大卫,我不想用界面生成器。那么,有什么解决办法吗?上面的代码可以初始化按钮并在不同的功能中使用它们吗?@Tauquir:你不必使用Interface Builder来遵循我的其余建议(尽管我确实建议这样做)。你的职能是什么?你确定它们是函数而不是方法吗?@David:事实上,我通过点击“点击我”按钮生成了两个按钮。为此,我在“loadView”中创建了“单击我”按钮。我再次调用一个函数“按下”来生成这两个按钮。我在函数“按下”中创建了第三个按钮“交换”。现在,当我单击这个“交换”按钮时,这些按钮应该被交换。@Tauquir:那么,当你单击“单击我”时,它调用一个名为“按下”的函数?我不确定您是如何做到这一点的,但是如果您将
按下
作为一个方法,您应该能够访问
按钮1
按钮2
,假设它们是实例变量。如果这样做没有帮助,我想你需要发布更多的代码,以便对正在发生的事情有更多的了解。@David-我正在使用------button addTarget:self action:@selector(buttonPressed)调用一个函数