從 Android 轉過來常有的落差之一,是 iOS 沒有那種「工具列式」的元件。想要一個外觀自訂的開關,最省事的做法同樣是繼承 UIButton,用兩張狀態圖切換。
加入兩張圖片:switch_off.png(關)與 switch_on.png(開)。
#import <UIKit/UIKit.h>
@interface UICustomSwitch : UIButton
@end
#import "UICustomSwitch.h"
@implementation UICustomSwitch
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setBackGroundImage];
}
return self;
}
- (void)setBackGroundImage {
[self setBackgroundImage:[UIImage imageNamed:@"switch_off.png"] forState:UIControlStateNormal];
[self setBackgroundImage:[UIImage imageNamed:@"switch_on.png"] forState:UIControlStateSelected];
[self addTarget:self action:@selector(touchUIInside:)
forControlEvents:UIControlEventTouchUpInside];
self.selected = NO; // 預設為關閉
}
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setBackGroundImage];
}
return self;
}
-(IBAction)touchUIInside:(id)sender {
UICustomSwitch *sw = (UICustomSwitch *)sender;
sw.selected = !sw.selected;
}
@end
結構與自訂 CheckBox 幾乎相同,唯一多出的細節是 setBackGroundImage 中把 selected 初始化為 NO,確保控制項建立時一律呈現「關」的狀態。若省略這行,在某些建立路徑下 UIButton 的預設狀態可能導致顯示不一致。
如果只是想呈現開關效果,其實 iOS 已內建 UISwitch,它自帶動畫、無障礙標記與 VoiceOver 支援,並能透過 onTintColor 調整色調,多數情況直接使用即可。自製的價值在於需要特殊視覺(例如遊戲風格、品牌插畫)時。
若決定自製,記得補上 isAccessibilityElement 與 accessibilityValue,讓螢幕閱讀器能正確朗讀目前是開還是關——少了這一步,自訂控制項對輔助使用者的可用性會大幅下降。