首页 > 解决方案 > 如何使用 Material (CosmicMind) 实现开关动作

问题描述

我正在尝试在我的应用程序中添加一个开关。我将它添加到情节提要中(IUView 与 Switch 类和 Material 模块。我在我的视图控制器中自定义了它,但我不知道如何对其执行操作。

我尝试使用 touch up inside 事件添加 IBAction,但是当我触摸它时我什么也没有。

谢谢。

我的代码:

import Foundation
import UIKit 
import Material

class SettingsVC: UIViewController {

    @IBOutlet weak var addCalendarSwitch: Switch!

    override func viewDidLoad() {
        super.viewDidLoad()

        addCalendarSwitch.delegate = self
        addObserver()
        setStyle()
        setView()
        getStatusAddCalendar()
    }

    func getStatusAddCalendar(){
        if UserDefaults.standard.bool(forKey: "addToCalendar") == true 
        {
            addCalendarSwitch.isOn = true
        }
        else {
            addCalendarSwitch.isOn = false
        }
    }
}

extension ViewController: SwitchDelegate {

    // utilise the delegate method
    func switchDidChangeState(control: Switch, state: SwitchState) {
        print("Switch changed state to: ", .on == state ? "on" : "off")
    }
}

等级制度

我的视图屏幕

标签: iosxcodecosmicmind

解决方案


查看示例,它似乎正在使用委托模式。 https://github.com/CosmicMind/Samples/blob/master/Projects/Programmatic/Switch/Switch/ViewController.swift

import UIKit
import Material

class ViewController: UIViewController {

    // create an outlet and connect it from your storyboard
    @IBOutlet weak var mySwitch: Switch!

    override func viewDidLoad() {
        super.viewDidLoad()
        // use this outlet to assign the delegate
        mySwitch.delegate = self
    }
}

// conform to the protocol
extension ViewController: SwitchDelegate {

    // utilise the delegate method
    func switchDidChangeState(control: Switch, state: SwitchState) {
        print("Switch changed state to: ", .on == state ? "on" : "off")
    }
}

推荐阅读