在我的应用程序中,我想在 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")
}
}
最佳答案
Crashing with Segmentation fault: 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()
内部。)
关于swift - 用户界面开关。段错误 : 11 with swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40134419/