用户界面开关。分段错误:11 swift
UISwitch. Segmentation fault: 11 with swift
在我的应用程序中,我想在 tableview 单元格中使用 UISwitch。当我尝试将目标添加到自定义开关时出现错误:"Segmentation fault: 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")
}
}
我想您忘记了将 cellSwitch 添加到 tableview 单元格中。这可能会导致 addTarget
到 self
的问题。
因 分段错误而崩溃: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()
内。)
我输入了您的代码并在 Xcode 7.3 中进行了编译,这一行导致了错误。
cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)
所以我将单元格开关声明从 let
更改为 lazy var
以便编译代码时不会出错。 ( 很好地解释了为什么这会导致编译错误)但我认为这可能不是您想要做的。您可以将 UISwitch 作为 IBOutlet 属性 添加到您的自定义 tableViewCell 中,并将您的 addTarget 操作代码移动到您的 viewController 中。
在我的应用程序中,我想在 tableview 单元格中使用 UISwitch。当我尝试将目标添加到自定义开关时出现错误:"Segmentation fault: 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")
}
}
我想您忘记了将 cellSwitch 添加到 tableview 单元格中。这可能会导致 addTarget
到 self
的问题。
因 分段错误而崩溃: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()
内。)
我输入了您的代码并在 Xcode 7.3 中进行了编译,这一行导致了错误。
cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)
所以我将单元格开关声明从 let
更改为 lazy var
以便编译代码时不会出错。 (