萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 自定義 CheckBox 控件完整實現:從繼承 UIControl 到委托回調

iOS 原生無 CheckBox 控件,常用 UISwitch 替代,但視覺風格差異大。通過繼承 UIControl 封裝圖標 + 標籤 + 點擊切換邏輯,可得原生級 CheckBox 體驗。

UICheckBoxButton.h

@protocol UICheckBoxButtonDelegate 
@optional
- (void)checkBoxButton:(UICheckBoxButton *)button didChangeChecked:(BOOL)checked;
@end

@interface UICheckBoxButton : UIControl

@property (nonatomic, weak) id delegate;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIImageView *icon;

@property (nonatomic, getter=isChecked) BOOL checked;

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title;
- (void)setChecked:(BOOL)checked animated:(BOOL)animated;

@end

UICheckBoxButton.m

@implementation UICheckBoxButton {
    UIImage *_checkedImage;
    UIImage *_uncheckedImage;
}

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title {
    self = [super initWithFrame:frame];
    if (self) {
        // 默認圖片(建議從 Asset Catalog 讀取 @2x/@3x)
        _uncheckedImage = [UIImage imageNamed:@"checkbox_unchecked"];
        _checkedImage = [UIImage imageNamed:@"checkbox_checked"];
        
        // 圖標
        _icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.height, frame.size.height)];
        _icon.contentMode = UIViewContentModeScaleAspectFit;
        _icon.image = _uncheckedImage;
        [self addSubview:_icon];
        
        // 標籤
        _label = [[UILabel alloc] initWithFrame:CGRectMake(_icon.frame.size.width + 8, 0, 
                                                          frame.size.width - _icon.frame.size.width - 8, 
                                                          frame.size.height)];
        _label.backgroundColor = [UIColor clearColor];
        _label.textAlignment = NSTextAlignmentLeft;
        _label.font = [UIFont systemFontOfSize:16];
        _label.textColor = [UIColor darkTextColor];
        _label.text = title;
        [self addSubview:_label];
        
        // 點擊事件
        [self addTarget:self action:@selector(toggleChecked) forControlEvents:UIControlEventTouchUpInside];
        
        // 無障礙
        self.accessibilityTraits = UIAccessibilityTraitButton | UIAccessibilityTraitSelected;
    }
    return self;
}

- (void)toggleChecked {
    [self setChecked:!self.checked animated:YES];
}

- (void)setChecked:(BOOL)checked animated:(BOOL)animated {
    if (checked == _checked) return;
    _checked = checked;
    
    // 更新圖標
    UIImage *targetImage = checked ? _checkedImage : _uncheckedImage;
    if (animated) {
        [UIView transitionWithView:_icon duration:0.15 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            _icon.image = targetImage;
        } completion:nil];
    } else {
        _icon.image = targetImage;
    }
    
    // 更新無障礙狀態
    self.accessibilitySelected = checked;
    
    // 回調委托
    [self.delegate checkBoxButton:self didChangeChecked:checked];
    
    // 發送 UIControlEventValueChanged 事件(支持 Target-Action)
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    // 子視圖佈局自適應
    _icon.frame = CGRectMake(0, 0, frame.size.height, frame.size.height);
    _label.frame = CGRectMake(_icon.frame.size.width + 8, 0, 
                              frame.size.width - _icon.frame.size.width - 8, 
                              frame.size.height);
}

@end

使用示例

// 在控制器中
UICheckBoxButton *agreeCheck = [[UICheckBoxButton alloc] initWithFrame:CGRectMake(20, 100, 300, 30) 
                                                                 title:@"我已閱讀並同意《用戶協議》"];
agreeCheck.delegate = self;
[self.view addSubview:agreeCheck];

// Target-Action 方式
[agreeCheck addTarget:self action:@selector(agreeCheckChanged:) forControlEvents:UIControlEventValueChanged];

// 委托方式
- (void)checkBoxButton:(UICheckBoxButton *)button didChangeChecked:(BOOL)checked {
    self.submitButton.enabled = checked;
}

// Target-Action
- (void)agreeCheckChanged:(UICheckBoxButton *)sender {
    NSLog(@"CheckBox 狀態: %@", sender.isChecked ? @"選中" : @"未選中");
}

進階擴展

  • 三態 CheckBox:未選/半選/全選(用於列表全選),增加 indeterminate 狀態與圖片。
  • 樣式主題化:通過 UIAppearance 代理統一設置圖片、字體、顏色。
  • Interface Builder 支持:添加 IBInspectable / IBDesignable 可在 Storyboard 直接配置預覽。
  • Swift 版:用 @IBDesignable + @IBInspectable 實現同樣效果。

避坑指南

  • ❌ 繼承 UIButton → 內部結構複雜(titleLabel、imageView 層級固定),難以精準控制佈局。
  • ❌ 直接用圖片切換無動畫 → 體生硬,加 transitionWithView 0.15s 淡入淡出極大提升質感。
  • ❌ 忽略無障礙 → VoiceOver 用戶無法識別狀態,必須設置 accessibilityTraits、accessibilitySelected。
  • ✅ 繼承 UIControl,語義正確、事件傳遞標準、佈局完全可控。

一個專業的 CheckBox,不僅「能勾選」,更要「好看、好用、無障礙、可維護」。

copyright © 萬盛學電腦網 all rights reserved