在IOS中以编程方式设置动作侦听器

Tah*_*lil 5 actionlistener uibutton uibarbuttonitem ios

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

Abi*_*ern 16

UIButton是UIControl的子类.

创建按钮后,您只需设置按钮的目标和操作即可.即

// 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];
Run Code Online (Sandbox Code Playgroud)

  • 它适用于iOS ..所以它是UIControl的子类吗?对? (2认同)

Mad*_*vad 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];
Run Code Online (Sandbox Code Playgroud)

然后正常创建处理程序:

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

-(void)navPrevButtonPressed
{
    NSLog(@"Prev pressed");
}
Run Code Online (Sandbox Code Playgroud)