能否为UIButton设置带字母的tag?有哪些可替代的实现方案?
实现方案
方案1:使用系统原生的accessibilityIdentifier属性(最推荐)
UIKit 控件本身自带字符串类型的标识属性,原本用于 UI 自动化测试和无障碍识别,完全可以用来做业务区分,不需要额外写扩展代码:
- OC 代码示例:
button1.accessibilityIdentifier = @"abc"; button2.accessibilityIdentifier = @"def"; // 取值判断 if ([button.accessibilityIdentifier isEqualToString:@"abc"]) { // 对应业务逻辑 }
- Swift 代码示例:
button1.accessibilityIdentifier = "abc" button2.accessibilityIdentifier = "def" // 取值判断 if button.accessibilityIdentifier == "abc" { // 对应业务逻辑 }
如果用 Interface Builder 开发,直接在控件的Identity 检查器里找到Accessibility->Identifier字段填写即可。
方案2:通过 Runtime 关联属性自定义字符串标识
如果你不想占用无障碍相关属性,可以给 UIButton 写分类扩展自定义的字符串标识属性:
- OC 分类实现示例:
// UIButton+CustomId.h @interface UIButton (CustomId) @property (nonatomic, copy) NSString *customId; @end // UIButton+CustomId.m #import <objc/runtime.h> @implementation UIButton (CustomId) static const void *kCustomIdKey = &kCustomIdKey; - (void)setCustomId:(NSString *)customId { objc_setAssociatedObject(self, kCustomIdKey, customId, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (NSString *)customId { return objc_getAssociatedObject(self, kCustomIdKey); } @end
使用时直接调用button.customId = @"abc"即可。
- Swift 扩展实现示例:
extension UIButton { private struct AssociatedKeys { static var customId: String = "customId" } var customId: String? { get { objc_getAssociatedObject(self, &AssociatedKeys.customId) as? String } set { objc_setAssociatedObject(self, &AssociatedKeys.customId, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } }
如果要在 IB 中直接设置自定义属性,可以通过 User Defined Runtime Attributes 配置,如下图:
方案3:枚举映射tag(无侵入替代方案)
如果不想改动原有基于 tag 的逻辑,可以定义枚举统一管理 tag 值,兼顾可读性和原生性能:
// Swift 示例 enum ButtonTag: Int { case abc = 1001 case def = 1002 case ghi = 1003 } // 赋值 button.tag = ButtonTag.abc.rawValue // 判断 if let tag = ButtonTag(rawValue: button.tag) { switch tag { case .abc: // 对应abc按钮逻辑 case .def: // 对应def按钮逻辑 default: break } }
内容的提问来源于stack exchange,提问作者liangdapang
相关产品推荐
相关产品推荐

