Swift4.0學(xué)習(xí)筆記(六)——開(kāi)關(guān)(UISwitch)

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è)置開(kāi)啟狀態(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īng)器
//添加狀態(tài)變化監(jiān)聽(tīng)器
switcher.addTarget(self, action: #selector(switchDidChange(_:)), for: .valueChanged)

@objc
func switchDidChange(_ sender: UISwitch){
      //打印當(dāng)前值
      print(sender.isOn)
}
添加狀態(tài)監(jiān)聽(tīng)器
3.switch狀態(tài)保存

switcher一般用來(lái)保存用戶的偏好設(shè)置,所以當(dāng)前switcher的狀態(tài)應(yīng)該能夠長(zhǎng)期有效,我們可以使用UserDefaults來(lái)存儲(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è)置開(kāi)啟狀態(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)聽(tīng)器
        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)保存起來(lái)

@objc
func switchDidChange(_ sender: UISwitch){
        //把當(dāng)前狀態(tài)保存起來(lái)
        UserDefaults.standard.set(sender.isOn, forKey: "switchState")
        //打印當(dāng)前值
        print(sender.isOn)
}

關(guān)于UISwitcher基本的用法以及保存狀態(tài)的方法就介紹到這里,更多更復(fù)雜的使用方法,小伙伴可以根據(jù)遇到的具體情況查資料

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容