连接按钮以编程方式查看控制器类objective-C

时间:2012-07-20 12:22:34

标签: objective-c ios xcode

  

可能重复:
  connect button to TableViewController in xcode

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

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

修改

这是我的编程按钮

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

3 个答案:

答案 0 :(得分:0)

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

addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

答案 1 :(得分: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");
 }

我认为这会对你有所帮助。

答案 2 :(得分:0)

您只需添加addTarget方法(请参阅此处:Bind Action to UI Button)。 在你的情况下,它将是:

[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(参见这里:Cocoa Notification Example)。通过这些,您可以将消息从一个类发送到另一个类,并对用户输入作出反应。

相关问题