0

可能重复:
将按钮连接到 xcode 中的 TableViewController

如何以编程方式将我的按钮连接到另一个视图控制器类提前谢谢,我需要代码我真的是初学者谢谢,这是我的按钮代码:我的 vie 控制器类名称是 year.m

-(void) year:(id)sender{
    NSLog(@"Year button clicked");
 }

编辑:

这是我的编程按钮的代码

UIBarButtonItem *yearButton= [[UIBarButtonItem alloc] initWithTitle:@"Year" style:UIBarButtonItemStyleBordered    
 target:self action:@selector(year:)];
4

3 回答 3

0

您可以简单地添加addTarget方法(请参阅此处:将操作绑定到 UI 按钮)。在您的情况下,它将是:

[yearButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

//the method that gets called
-(IBAction) buttonPressed: (id) sender {
  NSLog(@"Button clicked %@", sender);
  // do something here
}

但是如果你想检查按钮是否在另一个视图控制器中被按下,你必须寻找 NSNotifications (见这里:可可通知示例)。有了这些,您可以将消息从一个班级发送到另一个班级,并对用户的输入做出反应。

于 2012-07-20T12:58:45.620 回答
0

viewDidLoad按以下方式在方法中创建 yourButton ...

UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[yourButton setTitle:@"YearButton" forState:UIControlStateNormal];
yourButton.frame = CGRectMake(240, 40, 75, 30);     
[yourButton addTarget:self action:@selector(year:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:yourButton];

这是您的方法代码....

-(void) year:(id)sender{
    NSLog(@"Year button clicked");
 }

我想这会对你有所帮助。

于 2012-07-20T12:52:15.853 回答
0

要以编程方式添加目标/动作对(而不是通过 Interface Builder),请查看以下方法UIButton

addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
于 2012-07-20T12:30:26.060 回答