以下代碼直接訪問 UISwitch 內部私有視圖層級,不保證未來 iOS 版本兼容,App Store 審核可能拒絕。僅供學習/企業內部分發參考。
// 獲取 UISwitch 內部結構:UISwitch → UISwitchInternalView → 兩個 UILabel (On/Off)
UIView *internalView = self.mySwitch.subviews.lastObject; // UISwitchInternalView
UIView *labelsContainer = internalView.subviews[2]; // 包含 On/Off 標籤的容器
UILabel *onLabel = labelsContainer.subviews[0];
UILabel *offLabel = labelsContainer.subviews[1];
onLabel.text = @"開啟";
offLabel.text = @"關閉";
// 可選:調整字體/顏色
onLabel.font = [UIFont boldSystemFontOfSize:12];
offLabel.font = [UIFont systemFontOfSize:12];
onLabel.textColor = [UIColor whiteColor];
offLabel.textColor = [UIColor lightGrayColor];

UISwitch
└── UISwitchInternalView (私有類)
├── 滑塊層
├── 背景層
└── 包含 On/Off 標籤的容器 View
├── UILabel (On)
└── UILabel (Off)
索引位置可能隨 iOS 版本變化,極不穩定。
// CustomSwitch.h
@interface CustomSwitch : UIControl
@property (nonatomic, getter=isOn) BOOL on;
@property (nonatomic, copy) NSString *onTitle;
@property (nonatomic, copy) NSString *offTitle;
@property (nonatomic, strong) UIFont *titleFont;
@property (nonatomic, strong) UIColor *onColor;
@property (nonatomic, strong) UIColor *offColor;
- (void)setOn:(BOOL)on animated:(BOOL)animated;
@end
// 內部:兩個 UILabel + 滑塊 UIView + 觸摸/手勢處理 + 動畫
// 完全可控:文字、顏色、字體、動畫曲線、觸覺反饋
// 佈局:[Off Label] [UISwitch] [On Label]
// 代碼監聽 valueChanged 更新標籤顏色/狀態
[self.mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
- (void)switchChanged:(UISwitch *)sender {
self.offLabel.textColor = sender.isOn ? [UIColor lightGrayColor] : [UIColor blackColor];
self.onLabel.textColor = sender.isOn ? [UIColor blackColor] : [UIColor lightGrayColor];
}
UISwitch 在 iOS 14+ 新增 title 屬性,但僅支援單一標題顯示在開關旁邊,無法分別設置 On/Off 文字。
Toggle("開啟功能", isOn: $isOn)
.toggleStyle(SwitchToggleStyle(tint: .orange))
// 或自定義 ToggleStyle 實現任意視覺效果
| 方案 | 穩定性 | 靈活度 | 工作量 | 推薦 |
|---|---|---|---|---|
| 私有視圖 Hack | ❌ 極低 | 中 | 低 | 🚫 禁止生產 |
| 自定義 Switch | ✅ 最高 | ✅ 完全 | 中 | ⭐⭐⭐⭐⭐ |
| UISwitch + 外部 Label | ✅ 高 | 中 | 低 | ⭐⭐⭐⭐ 快速方案 |
| SwiftUI Toggle | ✅ 高 | 高 | 低 | ⭐⭐⭐⭐⭐ 新項目首選 |