5

嗨,我以编程方式创建了一个按钮。我将此按钮添加到导航栏。现在我想给它添加一个 Touch Up Inside 动作监听器。我该怎么做?谢谢。

4

2 回答 2

16

UIButton 是 UIControl 的子类。

创建按钮后,您需要做的就是设置按钮的目标和操作。IE

// Create your button:
UIButton *button = // However you create your button

// Set the target, action and event for the button
[button addTarget:// the object that implements the action method, or nil if you want it to propagate up the responder chain.
           action:// A selector for the method
 forControlEvents:UIControlEventTouchUpInside];
于 2012-12-02T12:02:53.767 回答
6

由于您已将它们添加到导航栏,因此略有不同,但基本相同。您将在创建按钮的同时添加侦听器/处理程序。在这里,我使用以下内容添加<<>>导航栏:

UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:@">>" style:UIBarButtonItemStylePlain target:self action:@selector(navNextButtonPressed)];
UIBarButtonItem *prevButton = [[UIBarButtonItem alloc] initWithTitle:@"<<" style:UIBarButtonItemStylePlain target:self action:@selector(navPrevButtonPressed)];
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:nextButton, prevButton, nil];

然后像往常一样创建你的处理程序:

#pragma mark - button handling
-(void)navNextButtonPressed
{    
    NSLog(@"Next pressed");
}

-(void)navPrevButtonPressed
{
    NSLog(@"Prev pressed");
}
于 2012-12-02T12:41:19.950 回答