【问题标题】:UISwitch Value change state issueUISwitch 值更改状态问题
【发布时间】:2019-08-26 02:01:09
【问题描述】:

我在我的应用程序中使用了UISwitchvalueChanged 目标,如下面的代码。 这个开关在我的UITableView

settingsTableCell.androidSwitchSmall.addTarget(self, action: #selector(switchStateChanged(_:)), for: .valueChanged)


@objc func switchStateChanged(_ mjSwitch: MJMaterialSwitch) {
    if self.lastSwitchState == mjSwitch.isOn {
        return
    }
    self.lastSwitchState = mjSwitch.isOn
    print(mjSwitch.isOn, mjSwitch.tag, "Small")
    self.changeTrackStatus()
}

我正在更改目标方法中 Switch 的值。所以它再次调用switchStateChanged方法。

但我只想在用户更改开关状态时调用switchStateChanged这个方法。

什么是最好的方法。

我如何区分天气用户更改了开关状态或开关状态以编程方式更改。

【问题讨论】:

  • UISwitch.setOn(mjSwitch)(true, animated: false)

标签: ios swift uiswitch


【解决方案1】:

按照步骤进行。

步骤 - 1

TabelView Cell里面做一个变量

var Btn1 : (()->())? 

步骤 - 2

TabelViewCell内创建UIButton的Action,并在上面调用Variable

@IBAction func cellbtn(_ sender: UIButton) {
        Btn1?()
 }

步骤 - 3

在您的View Controller 中声明一个Bool 变量和您的Function

var IsSwitchOn = false

 func switchStateChanged(_ mjSwitch: MJMaterialSwitch) {
    if self.IsSwitchOn {
        return
    }
    self.IsSwitchOn = True
    print(mjSwitch.isOn, mjSwitch.tag, "Small")
    self.changeTrackStatus()
}

步骤 - 4

请致电cellForRowAt indexPath

let cell = tableView.dequeueReusableCell(withIdentifier: "CellID") as! YourCell

cell.Btn1 = {
              () in
              Self.switchStateChanged()
        }

希望这有效。

【讨论】:

    【解决方案2】:

    您必须以编程方式发送操作, 您可以使用以下扩展名

    extension UISwitch {
        func set(on state: Bool, animated: Bool = true) {
            setOn(state, animated: animated)
            sendActions(for: .valueChanged)
        }
    }
    

    【讨论】:

      【解决方案3】:

      你为什么不使用 .touchUpInside 。这只会在用户与开关交互时触发选择器。

      settingsTableCell.androidSwitchSmall.addTarget(self, action: #selector(switchStateChanged(_:)), for: .touchUpInside)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-31
        • 2015-04-17
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多