Swift4.0学习笔记(六)——开关(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)
//设置开启状态显示的颜色
switcher.onTintColor = UIColor.red
//设置关闭状态的颜色
switcher.tintColor = UIColor.green
//滑块上小圆点的颜色
switcher.thumbTintColor = UIColor.yellow

运行效果如下:
on.png
off.png
2.添加状态监听器
//添加状态变化监听器
switcher.addTarget(self, action: #selector(switchDidChange(_:)), for: .valueChanged)

@objc
func switchDidChange(_ sender: UISwitch){
      //打印当前值
      print(sender.isOn)
}
添加状态监听器
3.switch状态保存

switcher一般用来保存用户的偏好设置,所以当前switcher的状态应该能够长期有效,我们可以使用UserDefaults来存储设置

UserDefaults.standard.set(sender.isOn, forKey: "switchState")

首先在AppDelegate中设置初始值

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        //设置初始值
        UserDefaults.standard.set(true, forKey: "switchState")
        return true
}

接着在定义的时候,获取这个值

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)
        //设置开启状态显示的颜色
        switcher.onTintColor = UIColor.red
        //设置关闭状态的颜色
        switcher.tintColor = UIColor.green
        //滑块上小圆点的颜色
        switcher.thumbTintColor = UIColor.yellow
        
        //添加状态变化监听器
        switcher.addTarget(self, action: #selector(switchDidChange(_:)), for: .valueChanged)
        //获取保存的状态值
        let state = UserDefaults.standard.bool(forKey: "switchState")
        switcher.setOn(state, animated: true)
    }

当switcher状态改变的时候应该把当前状态保存起来

@objc
func switchDidChange(_ sender: UISwitch){
        //把当前状态保存起来
        UserDefaults.standard.set(sender.isOn, forKey: "switchState")
        //打印当前值
        print(sender.isOn)
}

关于UISwitcher基本的用法以及保存状态的方法就介绍到这里,更多更复杂的使用方法,小伙伴可以根据遇到的具体情况查资料

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容