UISwitch。分段错误:11与swift

时间:2016-10-19 14:33:27

标签: swift xcode uiswitch

在我的应用程序中,我想在tableview单元格中使用UISwitch。当我尝试将目标添加到我的自定义开关时,我收到一个错误:"分段错误:11"。代码在下面。我该如何解决这个问题?

let cellSwitch: UISwitch = {
    let cellSwitch = UISwitch()
    cellSwitch.translatesAutoresizingMaskIntoConstraints = false
    cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)
    return cellSwitch
}()

func handleSwitch(_ mySwitch: UISwitch) {
    if mySwitch.isOn {
        print("On")
    } else {
        print("Off")
    }
}

3 个答案:

答案 0 :(得分:1)

崩溃分段错误:11 是Swift编译器的错误,您应该向Apple或swift.org发送错误报告。

在Swift 3中,代码中的某些错误通常会触发此编译器错误。

在您的情况下,您不能在实例属性的初始值中使用self。解决此问题的一种方法是使用lazy

lazy private(set) var cellSwitch: UISwitch = {
    let cellSwitch = UISwitch()
    cellSwitch.translatesAutoresizingMaskIntoConstraints = false
    cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)
    return cellSwitch
}()

另一种方法是将作业移至cellSwitch某处self可用。 (可能在viewDidLoad()内。)

答案 1 :(得分:0)

我认为您忘记将cellSwitch添加到tableview单元格。这可能会导致addTargetself的问题。

答案 2 :(得分:0)

我输入你的代码并在Xcode 7.3中编译,这一行导致错误。

cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)

所以我将单元格切换声明从let更改为lazy var,以便编译代码而不会出错。 (Here很好地解释了为什么会导致编译错误)但我认为这可能不是你想要做的。您可以在自定义tableViewCell中添加UISwitch作为IBOutlet属性,并在viewController中移动addTarget操作代码。