[英]Call a method completion block after button is tapped
我在單獨的類中創建了一個帶按鈕的popupView。 當在彈出視圖中點擊按鈕時,它應該進入完成處理程序內。
例。 UIAlertAction actionWithTitle:...:handler ^ {}; 這將使用OK按鈕打開alertView。 當點擊按鈕時,我將在完成處理程序中工作。
是否可以這樣創建,如果可以的話,如何在Objective-C中創建它。
我知道如何使用@protocol創建和設置類協議並調用方法。 我需要為許多視圖控制器使用此類,所以我不想在實現該類的任何地方調用協議方法。
您可以嘗試使用塊(目標C)
創建一個帶塊的屬性,在創建彈出視圖的地方編寫以下代碼。
@property (nonatomic, strong) void (^actionHandler)(void);
在操作按鈕中-
- (IBAction)doneButtonAction:(id)sender {
_actionHandler();
}
//當顯示popView時,您定義處理程序
[popView setActionHandler:^{
// DO Whatever you want, you just need to write this whenever you show pop view, rest code only once.
}];
使用完成處理程序創建函數
-迅捷3-
func action(completion:@escaping (_:Bool) -> Void) {
}
action { (success) in
}
-目標C-
- (void)action:(void (^)(bool success))completionHandler {
}
[self action:^(bool success) {
}];
我創建了兩個單獨的類,ViewController.h和PopupViewController.h
請查看代碼:
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m
#import "ViewController.h"
#import "PopupViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)btnOkPressed:(id)sender
{
PopupViewController *master=[PopupViewController sharedInstance];
[self presentViewController:master animated:YES completion:^{
}];
[master callCompletion:^(NSString *str) {
NSLog(@"%@",str);
[master dismissViewControllerAnimated:YES completion:^{
}];
}];
}
@end
PopupViewController.h
#import <UIKit/UIKit.h>
typedef void(^Completionhandler)(NSString* str);
@interface PopupViewController : UIViewController
+(PopupViewController*)sharedInstance;
-(void)callCompletion:(Completionhandler)handler;
@end
PopupViewController.m
#import "PopupViewController.h"
@interface PopupViewController ()
{
@private
Completionhandler _myHandler;
}
@end
@implementation PopupViewController
+(PopupViewController*)sharedInstance
{
static PopupViewController *popup=nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
popup = [[PopupViewController alloc] initWithNibName:@"PopupViewController" bundle:nil];
});
return popup;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)btnOkPressed:(id)sender
{
_myHandler(@"test msg");
}
-(void)callCompletion:(Completionhandler)handler
{
_myHandler = handler;
}
@end
我希望你能得到答案,如果您有任何疑問,請隨時問我.. :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.