如何处理自定义视图的按钮点击事件?

时间:2017-04-08 05:19:50

标签: ios objective-c custom-controls

我想在我的项目中执行以下概念:

我刚刚使用UIViewController创建了一个小型自定义弹出窗口,此自定义 弹出窗口包含一个消息标签和两个按钮,一个是"确定&# 34;另一个是"取消"。这个自定义 弹出编码在 appdelegate 中进行。现在当我想打开这个弹出窗口时,我只需要在 viewcontroller 中调用此 appdelegate 弹出窗口方法,当我需要打开此警报时。

现在的问题是,我想在" OK"上执行不同的功能。 "自定义提醒按钮"弹出。所以请帮助我如何管理这个" Ok"来自Individual ViewController的按钮单击事件。

请查看我附带的屏幕截图 [![在此处输入图像说明] [1]] [1]

先谢谢

1 个答案:

答案 0 :(得分:1)

将下面的方法放在Utility类中,并从视图控制器中调用它,如

[Utility showAlertWithTitle:@"ABC" msg:@"msg" vc:self positiveHandler:^(UIAlertAction *action) {
  // Do here when ok is pressed
} negativeHandler:nil]; //pass nil when cancel is pressed

ObjC

+ (void)showAlertWithTitle:(NSString *)title msg:(NSString *)msg vc:(UIViewController *)vc positiveHandler:(void (^ __nullable)(UIAlertAction *action))positiveHandler negativeHandler:(void (^ __nullable)(UIAlertAction *action))negativeHandler {
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];

  UIAlertAction *positiveAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:positiveHandler];
  [alertController addAction:positiveAction];

  UIAlertAction *negativeAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:negativeHandler];
  [alertController addAction:negativeAction];

  //show alert
  [vc presentViewController:alertController animated:YES completion:nil];
}

夫特

 // Shows alert with yes no button
 static func showAlert(title: String, msg: String, vc: UIViewController, positiveActionHandler: ((UIAlertAction) -> Swift.Void)?, negativeActionHandler: ((UIAlertAction) -> Swift.Void)?) {
 let alertController = UIAlertController(title: title, message: msg, preferredStyle: .alert)
 let positiveAction = UIAlertAction(title: "Ok", style: .destructive, handler: positiveActionHandler)
 alertController.addAction(positiveAction)

 let negativeAction = UIAlertAction(title: "Cancel", style: .cancel, handler: negativeActionHandler)
 alertController.addAction(negativeAction)
 vc.present(alertController, animated: true, completion: nil)
 }