我尝试在给定初始值的swift中动态生成按钮,大小为8的数组将生成8个按钮。
然而,即使代码有效,每当我点击任何生成的按钮时,应用程序会立即崩溃并显示错误代码"线程1信号SIGABRT"并且控制台读取" libc ++ abi.dylib:以NSException"类型的未捕获异常终止。
然后我指向包含"类AppDelegate的行:UIResponder,UIApplicationDelegate {"在AppDelegate.swift中。
我已尝试过在其他类似问题中看到的建议,但无济于事,请参阅下面的代码
func generateButtons (){
var numberOfVillains = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
var buttonY: CGFloat = 126 // our Starting Offset, could be 0
for number in numberOfVillains {
let segmentController = UISegmentedControl()
//let villainButton = UISegmentedControl(frame: CGRect(x: 50, y: buttonY, width: 50, height: 30)){
buttonY = buttonY + 40 // we are going to space these UIButtons 50px apart
segmentController.frame = CGRect(x:160, y:buttonY, width: 100,height: 30)
//segment frame size
segmentController.insertSegment(withTitle: "Off", at: 0, animated: true)
//inserting new segment at index 0
segmentController.insertSegment(withTitle: "On", at: 1, animated: true)
//inserting new segment at index 1
segmentController.backgroundColor = UIColor.white
//setting the background color of the segment controller
segmentController.selectedSegmentIndex = 0
//setting the segment which is initially selected
segmentController.addTarget(self, action: Selector(("segment:")), for: UIControlEvents.valueChanged)
//calling the selector method
self.view.addSubview(segmentController)
//adding the view as subview of the segment comntroller w.r.t. main view controller
}
}
func buttonPressed(sender: UISegmentedControl!) {
print("ButtonIsSelected")
}
答案 0 :(得分:3)
您正在按钮上设置选择器的目标(("段:"))。但是,您为处理点击而添加的方法称为buttonPressed()
将选择器(("段:"))更改为选择器(" buttonPressed:"),这应解决问题
答案 1 :(得分:1)
事情需要看起来像这样:
class ViewController: UIViewController {
func generateButtons (){
...
}
@objc func buttonPressed(sender: UISegmentedControl!) {
print("ButtonIsSelected")
}
}
而不是这样:
class ViewController: UIViewController {
func generateButtons (){
...
}
}
@objc func buttonPressed(sender: UISegmentedControl!) {
print("ButtonIsSelected")
}
另外,要使编译器警告静音,请尝试更改行:
segmentController.addTarget(self, action: Selector(("buttonPressed:")), for: UIControlEvents.valueChanged)
为:
segmentController.addTarget(self, action: #selector(buttonPressed), for: UIControlEvents.valueChanged)
答案 2 :(得分:0)
我认为我已经发现了问题,显然你为生成的按钮引用的函数不需要包含“:”,也不包含任何括号,如果它不包含任何参数,那么正确的格式是
segmentController.addTarget(self, action: #selector(ViewController.buttonPressed), for: .valueChanged)
而不是
segmentController.addTarget(self, action: Selector(("buttonPressed:")), for: UIControlEvents.valueChanged)'