萬盛學電腦網

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

iOS 修改 UISwitch 開關文字:私有視圖層級 Hack 與正規替代方案

⚠️ 警告:私有 API 風險

以下代碼直接訪問 UISwitch 內部私有視圖層級,不保證未來 iOS 版本兼容,App Store 審核可能拒絕。僅供學習/企業內部分發參考。

Hack 代碼 (iOS 7-10 有效,iOS 11+ 可能失效)


// 獲取 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 效果

結構解析 (iOS 10 參考)

UISwitch
└── UISwitchInternalView (私有類)
    ├── 滑塊層
    ├── 背景層
    └── 包含 On/Off 標籤的容器 View
        ├── UILabel (On)
        └── UILabel (Off)

索引位置可能隨 iOS 版本變化,極不穩定。

正規替代方案 (100% 安全、App Store 合規)

方案一:自定義 Switch 控件 (推薦)


// 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 + 觸摸/手勢處理 + 動畫
// 完全可控:文字、顏色、字體、動畫曲線、觸覺反饋

方案二:UISwitch + 外部標籤 (最簡單)


// 佈局:[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];
}

方案三:iOS 14+ UISwitch 原生支援標題 (有限)

UISwitch 在 iOS 14+ 新增 title 屬性,但僅支援單一標題顯示在開關旁邊,無法分別設置 On/Off 文字。

方案四:SwiftUI Toggle (全平台原生)


Toggle("開啟功能", isOn: $isOn)
    .toggleStyle(SwitchToggleStyle(tint: .orange))
// 或自定義 ToggleStyle 實現任意視覺效果

總結建議

方案穩定性靈活度工作量推薦
私有視圖 Hack❌ 極低中低🚫 禁止生產
自定義 Switch✅ 最高✅ 完全中⭐⭐⭐⭐⭐
UISwitch + 外部 Label✅ 高中低⭐⭐⭐⭐ 快速方案
SwiftUI Toggle✅ 高高低⭐⭐⭐⭐⭐ 新項目首選
copyright © 萬盛學電腦網 all rights reserved