-1
    @IBOutlet var button: UIButton!    
    func randomize(){
        var x_axis:CGFloat = 8.0
        var y_axis:CGFloat = 330.0
        for selected_Synonym in selected_Synonyms {
            button = UIButton.init(type: UIButtonType.custom) as UIButton
            button.frame = CGRect(x: x_axis, y: y_axis, width: 400, height: 50)
            button.backgroundColor = UIColor.black
            button.setTitle(selected_Synonym as? String, for: UIControlState.normal)
            button.setTitleColor(UIColor.white, for: [])
            button.addTarget(self, action: Selector(("pressed:")), for: UIControlEvents.touchUpInside)
            self.view.addSubview(button)
            x_axis = 10.0
            y_axis += 70.0
        }
    }

    func pressed(sender: Any){
        let buttonTitle = button.currentTitle
        print(buttonTitle)
    }

However when it runs and I press on a button I get the following error:

Thread 1: signal SIGABRT.

The program creates 5 buttons. I am new to swift and ios development would be very grateful if someone could help me out. Thank you.

recnac
  • 3,744
  • 6
  • 24
  • 46
  • See https://stackoverflow.com/questions/51469740/unrecognized-selector-sent-to-instance-for-my-tap-gesture. See also: https://stackoverflow.com/questions/36211030/whats-the-advantage-of-selector-update-in-swift-2-3 – matt Jul 31 '18 at 16:19

1 Answers1

2

You have several issues. To fix the crash, replace Selector(("pressed:")) with #selector(pressed). The use of Selector is very out-of-date. Always use #selector.

Next, remove the @IBOutlet var button: UIButton! line. You don't need it.

Then change:

button = UIButton.init(type: UIButtonType.custom) as UIButton

to:

let button = UIButton(type: .custom)

Then update your pressed function to:

@objc func pressed(sender: UIButton){
    let buttonTitle = sender.currentTitle
    print(buttonTitle)
}

Note the addition of @objc. This is required for any function being used with a target/selector. Also note that sender is now UIButton instead of Any. It's best to set the sender's type to match the proper type.

Here's all of your code with lots of little fixes:

func randomize() {
    var xAxis: CGFloat = 8.0
    var yAxis: CGFloat = 330.0

    for selectedSynonym in selectedSynonyms {
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: xAxis, y: yAxis, width: 400, height: 50)
        button.backgroundColor = .black
        button.setTitle(selectedSynonym, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(pressed), for: .touchUpInside)
        self.view.addSubview(button)
        xAxis = 10.0
        yAxis += 70.0
    }
}

@objc func pressed(sender: UIButton){
    let buttonTitle = sender.currentTitle
    print(buttonTitle)
}

Use camelCase, not snake_case when naming variables and functions. Make use of Swift type inference.

rmaddy
  • 314,917
  • 42
  • 532
  • 579