单击时以编程方式生成的按钮使应用程序崩溃。

buttons generated programmatically crash app when clicked.

我正在尝试在给定初始值的 swift 中动态生成按钮,大小为 8 的数组将生成 8 个按钮。

但是,即使代码有效,每当我单击任何生成的按钮时,应用程序都会立即崩溃并显示错误代码 "thread 1 signal SIGABRT" 并且控制台显示 "libc++abi.dylib: terminating with uncaught exception of type NSException"。

然后我指向 AppDelegate.swift 中包含 "class AppDelegate: UIResponder, UIApplicationDelegate {" 的行。

我已经尝试了其他类似问题中看到的建议,但无济于事,请参见下面的代码

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")
}

您正在按钮上设置 Selector(("segment:")) 的目标。但是你添加的处理点击的方法叫做 buttonPressed()

将 Selector(("segment:")) 更改为 Selector("buttonPressed:"),这应该可以解决问题

事情应该是这样的:

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)

我想我已经找到了问题,显然你为生成的按钮引用的函数不需要包含“:”,如果它不接受任何参数,也不需要任何括号,而且,正确的格式是

segmentController.addTarget(self, action: #selector(ViewController.buttonPressed), for: .valueChanged)

相对于

segmentController.addTarget(self, action: Selector(("buttonPressed:")), for: UIControlEvents.valueChanged)'