1.聲明控件
//定義控件x:30 y:100 width:80 height:40
let switcher = UISwitch(frame: CGRect(x: 30, y: 100, width: 80, height: 40))
self.view.addSubview(switcher)
//設(shè)置開啟狀態(tài)顯示的顏色
switcher.onTintColor = UIColor.red
//設(shè)置關(guān)閉狀態(tài)的顏色
switcher.tintColor = UIColor.green
//滑塊上小圓點(diǎn)的顏色
switcher.thumbTintColor = UIColor.yellow
運(yùn)行效果如下:on.png
off.png
2.添加狀態(tài)監(jiān)聽器
//添加狀態(tài)變化監(jiān)聽器
switcher.addTarget(self, action: #selector(switchDidChange(_:)), for: .valueChanged)
@objc
func switchDidChange(_ sender: UISwitch){
//打印當(dāng)前值
print(sender.isOn)
}
添加狀態(tài)監(jiān)聽器
3.switch狀態(tài)保存
switcher一般用來保存用戶的偏好設(shè)置怠晴,所以當(dāng)前switcher的狀態(tài)應(yīng)該能夠長期有效舍悯,我們可以使用UserDefaults來存儲(chǔ)設(shè)置
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
首先在AppDelegate中設(shè)置初始值
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//設(shè)置初始值
UserDefaults.standard.set(true, forKey: "switchState")
return true
}
接著在定義的時(shí)候领跛,獲取這個(gè)值
override func viewDidLoad() {
super.viewDidLoad()
//定義控件x:30 y:100 width:80 height:40
let switcher = UISwitch(frame: CGRect(x: 30, y: 100, width: 80, height: 40))
self.view.addSubview(switcher)
//設(shè)置開啟狀態(tài)顯示的顏色
switcher.onTintColor = UIColor.red
//設(shè)置關(guān)閉狀態(tài)的顏色
switcher.tintColor = UIColor.green
//滑塊上小圓點(diǎn)的顏色
switcher.thumbTintColor = UIColor.yellow
//添加狀態(tài)變化監(jiān)聽器
switcher.addTarget(self, action: #selector(switchDidChange(_:)), for: .valueChanged)
//獲取保存的狀態(tài)值
let state = UserDefaults.standard.bool(forKey: "switchState")
switcher.setOn(state, animated: true)
}
當(dāng)switcher狀態(tài)改變的時(shí)候應(yīng)該把當(dāng)前狀態(tài)保存起來
@objc
func switchDidChange(_ sender: UISwitch){
//把當(dāng)前狀態(tài)保存起來
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
//打印當(dāng)前值
print(sender.isOn)
}
關(guān)于UISwitcher基本的用法以及保存狀態(tài)的方法就介紹到這里,更多更復(fù)雜的使用方法假褪,小伙伴可以根據(jù)遇到的具體情況查資料