UISwitch价值改变状态问题

问题描述 投票:0回答:3

我在我的应用程序中使用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这个方法。

什么是最好的方式。

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

ios swift uiswitch
3个回答
0
投票

按照步骤。

步骤1

TabelView Cell里面做一个变量

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

第2步

TabelViewCell中创建UIButton的动作并在Variable上面调用。

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

第3步

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

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()
        }

希望这项工作。


0
投票

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

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

0
投票

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

settingsTableCell.androidSwitchSmall.addTarget(self, action: #selector(switchStateChanged(_:)), for: .touchUpInside)
© www.soinside.com 2019 - 2024. All rights reserved.