利用UIControl內建的Target-Action機制,定義自定義控件事件常量(UIControlEvents擴展位),調用sendActionsForControlEvents:觸發,使用者通過addTarget:action:forControlEvents:註冊響應。
// SocketUtils.h #import@interface SocketUtils : UIControl @end // 自定義事件常量(UIControlEventApplicationReserved位段) enum { UIControlEventCustomAlert = 0x00000001 << 24, // 0x01000000 UIControlEventCustomError = 0x00000001 << 25 // 0x02000000 };
// SocketUtils.m
- (void)someAsyncCallback {
// 觸發自定義事件
[self sendActionsForControlEvents:UIControlEventCustomAlert];
}
// Head.h #import#import "SocketUtils.h" @interface Head : UIView @property (nonatomic, strong) SocketUtils *socketUtils; @end // Head.m @implementation Head @synthesize socketUtils = _socketUtils; - (instancetype)init { self = [super init]; if (self) { _socketUtils = [[SocketUtils alloc] init]; // 關鍵:註冊Target-Action [_socketUtils addTarget:self action:@selector(socketEvent:) forControlEvents:UIControlEventCustomAlert]; } return self; } - (void)socketEvent:(SocketUtils *)sender { NSLog(@"收到自定義事件: %@", sender); } @end
UIControl:獲得addTarget:action:forControlEvents:、sendActionsForControlEvents:完整機制UIControlEventApplicationReserved位段(24-27位),避免與系統事件衝突- (void)action:(id)sender,sender即發送事件的控件| 優點 | 缺點 |
|---|---|
| 零成本復用成熟機制 | 參數固定,無法自定義攜帶數據 |
| 支持多目標廣播 | 事件常量位段有限(僅4位) |
| 系統框架原生支持 | 需繼承UIControl,不適用於非View對象 |