【问题标题】:Swift - UISwitch not updating when toggled On/OffSwift - 切换开/关时 UISwitch 不更新
【发布时间】:2016-07-20 17:00:09
【问题描述】:

我正在尝试以编程方式创建 UISwitch(没有 IBOutlets 或 IBActions),但我似乎无法弄清楚如何让开关在按下时更改状态。我还以为...

mySwitch.addTarget() 

... 每次打开/关闭开关时都会调用,但情况似乎并非如此。有人可以解释我做错了什么以及如何纠正这个问题。

import UIKit
import XCPlayground

let view = UIView(frame: CGRect(x: 0, y: 0, width: 320 * 0.75, height: 568 * 0.75))

view.backgroundColor = UIColor.whiteColor()
view.layer.borderColor = UIColor.grayColor().CGColor
view.layer.borderWidth = 1

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 320 * 0.75, height: 50))

label.text = "Label"
label.textAlignment = NSTextAlignment.Center

view.addSubview(label)

func switchChanged(sender: UISwitch!) {
    if sender.on == true {
        label.text = "Switch is ON"
    } else if sender.on == false {
        label.text = "Switch is OFF"
    }
}

let mySwitch = UISwitch()

mySwitch.center = view.center
mySwitch.setOn(true, animated: false)
mySwitch.onTintColor = UIColor.redColor()
mySwitch.addTarget(label, action: Selector(switchChanged(mySwitch)), forControlEvents: UIControlEvents.ValueChanged)

view.addSubview(mySwitch)

XCPlaygroundPage.currentPage.liveView = view

【问题讨论】:

    标签: ios swift cocoa-touch uiswitch addtarget


    【解决方案1】:

    您需要对此行进行一些修复:

    mySwitch.addTarget(label, action: Selector(switchChanged(mySwitch)), forControlEvents: UIControlEvents.ValueChanged)
    

    要使addTarget 工作,您需要一个响应操作的实例。显然label 不会回复switchChanged

    将您的操作方法包含在一个类中:

    class MyTarget {
        @objc func switchChanged(sender: UISwitch!) {
            if sender.on == true {
                label.text = "Switch is ON"
            } else if sender.on == false {
                label.text = "Switch is OFF"
            }
        }
    }
    

    另一个问题是Selector.init的用法,如果你写Selector(switchChanged(mySwitch)),Swift会执行参数switchChanged(mySwitch),然后将结果传递给Selector.init。 虽然switchChanged 的返回类型是Void,但您的代码几乎与编写Selector() 相同。

    尽量使用#selector 表示法。这种情况下,有了上面介绍的类,就可以写成#selector(MyTarget.switchChanged)了。

    所以,要正确地addTarget,您需要将行更改为:

    let target = MyTarget()
    mySwitch.addTarget(target, action: #selector(MyTarget.switchChanged), forControlEvents: .ValueChanged)
    

    我的 Xcode 有点顽固,我需要重新启动 Xcode 才能查看实时视图时间线,但是,通过这些更改,我相信您的代码可以按预期工作。

    【讨论】:

      【解决方案2】:
      mySwitch.addTarget(label, action: Selector(switchChanged(mySwitch)), forControlEvents: UIControlEvents.ValueChanged)
      

      但它不是包含switchChanged 函数的标签:它是

      在实际的应用项目(即不是游乐场)中正确配置它会更好。您将拥有一个可以充当self 并且可以成为目标的视图控制器。

      【讨论】:

      • 不要尝试在操场上进行这种严肃的互动。这就像亲吻青蛙:什么都没有发生,这让青蛙很恼火。
      猜你喜欢
      • 2018-09-28
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多