【问题标题】:how do implement action on switch with Material (CosmicMind)如何使用 Material (CosmicMind) 实现开关动作
【发布时间】:2018-11-20 16:51:27
【问题描述】:

我正在尝试在我的应用中添加一个开关。我在情节提要中添加了它(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")
    }
}

hierarchy

screen of my view

【问题讨论】:

    标签: ios xcode cosmicmind


    【解决方案1】:

    查看示例,它似乎正在使用委托模式。 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")
        }
    }
    

    【讨论】:

    • 是的,我看到了这个,但我是新手,我不知道如何使用我在情节提要中的 switch 来做到这一点
    • 我已经更新了示例。要从控制器中的情节提要访问开关,您需要创建一个 IBOutlet 并连接它。然后您可以分配委托并提供委托方法,如图所示。
    • 好的,谢谢,我试过了,但首先,我必须公开函数 switchDidChangeState " 方法 'switchDidChangeState(control:state:)' 必须声明为 public,因为它符合公共协议 'SwitchDelegate 中的要求'”,如果我把 mySwitch.delegate = self,self 是我的视图控制器,我有这个错误“无法将类型 'SettingsVC' 的值分配给类型'SwitchDelegate?' "
    • 不幸的是,没有看到您的任何代码,很难提供帮助。如果您想查看/比较您的实现,我已经创建了一个带有故事板的简单示例。 transfernow.net/279i98h0g14f
    • 谢谢,我比较了我的代码,我认为我有同样的事情。我已经用我的代码编辑了我的查询。有了那个代码,我就有了我之前写的两个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多