-1

I've created a UIButton programmatically as shown below:

let buttons: [UIButton] = [UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))];

Now if I try to add a function to it programmatically like this:

[buttons[0] addTarget:self action:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside]

I get an error saying that addTarget is not defined. How do I fix this?

4

2 回答 2

2

you are try to use the Objective-C syntax in swift, this is entirely wrong, use your code as like

 buttons.first?.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)

and handle the action as like

 @objc func buttonClicked( _ sender: UIButton) {
       print("buttonClicked Action Found")

}

Ref : Apple Document for UIButton

于 2019-03-07T04:24:49.450 回答
0

First of all you are creating [UIButton] which is Array of UIButton and it's not a single Button.

You can not create Array of UIButton that way. You will need a for loop for that and you need to update the frame accordingly.

And you can create a single UIButton this way:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

then you can add it into the UIView this way:

self.view.addSubview(button)

Without above line it your button will not show into your screen.

Next if you want to add action to that button you can do it by adding this line in your button code:

button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)

and it will need a helper method which will execute when button will click.

@objc func buttonClicked(_ sender: UIButton) {
    //Perform your action when button is clicked.
}

And you also need to apply backgroundColor and setTitle to the button.

and your final code will look like:

let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = UIColor.green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
于 2019-03-07T05:38:36.843 回答