ios - 如何处理自定义 View 的按钮点击事件?

标签 ios objective-c custom-controls

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

我刚刚使用 UIViewController 创建了一个小的自定义弹出窗口,这个自定义 popup 包含一个消息标签和两个按钮,一个是“OK”另一个是“取消”。此自定义 弹出 代码在appdelegate 中执行。现在,当我想打开这个弹出窗口时,当我需要打开这个警报时,我只是从 viewcontroller 调用了这个 appdelegate 弹出方法。

现在的问题是,我想在“自定义警报”弹出窗口的“确定”按钮上执行不同的功能。因此,请帮助我如何管理来自 Individual ViewController 的“确定”按钮单击事件。

最佳答案

将下面的方法放在 Utility 类中,然后从您的 View Controller 中调用它

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

对象

+ (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];
}

swift

 // 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)
 }

关于ios - 如何处理自定义 View 的按钮点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43290484/

相关文章:

ios - 在 Objective-C 上使用 Enum 和 Switch

ios - 在 iOS 中将 "1/31/2016 5:53:21 AM"格式化为 "31 Jan' 16"

android - 布局描述中 "$"字符连接两个组件是什么意思?

cocoa - 如何创建自定义 NSView 的缩小版本

ios - 将 NSLayoutConstraint 常量重置为其 Storyboard 中的原始值

ios - skmaps 通过更新 SKAnnotation 来解决巨大的内存泄漏

javascript - 跨源图像加载被拒绝 - 仅限 iPhone - 简单图像上传

ios - 如何从 iPhone 上的 UIWebView 的 HTML 引用本地镜像文件?

java - 从 Cocoa 应用程序调用 Java 程序

c# - ResourceDictionary 中的自定义 TabItem