首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C自定義事件實現:基於UIControl的Target-Action擴展

     編輯:關於C語言

Objective-C自定義事件實現:基於UIControl的Target-Action擴展

核心思路

利用UIControl內建的Target-Action機制,定義自定義控件事件常量(UIControlEvents擴展位),調用sendActionsForControlEvents:觸發,使用者通過addTarget:action:forControlEvents:註冊響應。

實現步驟

1. 自定義事件枚舉(擴展位24-27)

// SocketUtils.h
#import 

@interface SocketUtils : UIControl
@end

// 自定義事件常量(UIControlEventApplicationReserved位段)
enum {
    UIControlEventCustomAlert = 0x00000001 << 24, // 0x01000000
    UIControlEventCustomError = 0x00000001 << 25  // 0x02000000
};

2. 觸發事件

// SocketUtils.m
- (void)someAsyncCallback {
    // 觸發自定義事件
    [self sendActionsForControlEvents:UIControlEventCustomAlert];
}

3. 使用者註冊響應

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

關鍵技術點

  1. 繼承UIControl:獲得addTarget:action:forControlEvents:、sendActionsForControlEvents:完整機制
  2. 事件常量選擇:使用UIControlEventApplicationReserved位段(24-27位),避免與系統事件衝突
  3. 參數傳遞:Action方法簽名固定為- (void)action:(id)sender,sender即發送事件的控件
  4. 多目標支持:同一事件可註冊多組target-action

優缺點對比

替代方案

  • NotificationCenter:跨層級廣播,攜帶userInfo字典
  • Delegate協議:一對一,豐富參數,編譯期檢查
  • Block回調:內聯代碼,靈活參數,需防循環引用
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
優點缺點
零成本復用成熟機制參數固定,無法自定義攜帶數據
支持多目標廣播事件常量位段有限(僅4位)
系統框架原生支持需繼承UIControl,不適用於非View對象