addTarget to custom button Swift 4 - ios

I have a problem with addTarget to my custom button in Swift 4. I tried everything, but still have problem to define selector, because result is always error.
Any idea?
let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
myButton.center = CGPoint(x: 200, y: 400)
myButton.backgroundColor = UIColor.purple
myButton.layer.cornerRadius = 18.0
myButton.setTitle("Tap Me", for: UIControlState.normal)
myButton.setTitleColor(UIColor.white, for: UIControlState.normal)
myButton.actions(forTarget: self, forControlEvent: UIControlEvents.touchUpInside)
myButton.isHighlighted = true
self.view.addSubview(myButton)

Try this
myButton.addTarget(self, action: #selector(self.btnClickAction(_:)), for: .touchUpInside)
Button action method
#objc func btnClickAction(_ sender:UIButton) {
print("My custom button action")
}

Related

How to assign a button’s action in code using #objc mark for given function?

Hi for this question I found answer on How to create a button programmatically? however still facing the errors: "Argument of '#selector' cannot refer to local function 'plusOne(sender:)'" and "#objc can only be used with members of classes, #objc protocols, and concrete extensions of classes". If you can advice.
let button = UIButton()
button.frame = CGRect(x: 150, y: 300, width: 60, height: 60)
button.setTitle("Click", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(plusOne), for: .touchUpInside)
self.view.addSubview(button)
#objc func plusOne(sender: UIButton!) {
self.count += 1
self.label.text = "\(self.count)"
}
The problem you have is that you've nested the #objc func plusOne(sender: UIButton!) within viewDidLoad (which was why i asked the initial question about scope). You need to move it out to a class-scope method.
override func viewDidLoad() {
// all the usual stuff...
let button = UIButton()
button.frame = CGRect(x: 150, y: 300, width: 60, height: 60)
button.setTitle("Click", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(plusOne), for: .touchUpInside)
self.view.addSubview(button)
}
#objc func plusOne(sender: UIButton!) {
self.count += 1
self.label.text = "\(self.count)"
}
The name of the method is plusOne(sender:), the argument labels make part of the name

i want to connect radio button method with selector statement in swift

let button8:ISRadioButton = ISRadioButton(frame: CGRect(x: 140, y: 75, width: 70, height: 35))
button8.addTarget(self, action:#selector(buttonClicked4), for: .touchUpInside)
button8.setTitle("Female", for: .normal)
button8.setTitleColor(UIColor.black, for: .normal)
button8.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
// method for radio button
#objc func buttonClicked4(_ isRadioButton:ISRadioButton){
if isRadioButton.multipleSelectionEnabled{
for radioButton in isRadioButton.otherButtons! {
print("%# is selected.\n", radioButton.titleLabel!.text ?? "");
}
}else{
print("%# is selected.\n", isRadioButton.titleLabel!.text ?? "");
}
}
i want to connect radio button method with selector statement but through this code method is not executing
After reviewing your code and then testing it for myself, I believe that the issue has to do with addTarget method. Your function includes _ isRadioButton: ISRadioButton, but when you add it to your target you use buttonClicked4. If you notice, there is nothing after this is declared. So you need to include (_:) after you declare your function in the addTarget method.
Your code should come out to the following:
let button8: ISRadioButton = ISRadioButton(frame: CGRect(x: 140, y: 75, width: 70, height: 35))
// Changed buttonClicked4 to buttonClicked4(_:)
button8.addTarget(self, action: #selector(buttonClicked4(_:)), for: .touchUpInside)
button8.setTitle("Female", for: .normal)
button8.setTitleColor(UIColor.black, for: .normal)
button8.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
#objc func buttonClicked4(_ isRadioButton: ISRadioButton) {
if isRadioButton.multipleSelectionEnabled {
for radioButton in isRadioButton.otherButtons! {
print("%# is selected.\n", radioButton.titleLabel!.text ?? "")
}
} else {
print("%# is selected.\n", isRadioButton.titleLabel!.text ?? "")
}
}

The UIButton on UIToolBar seems to be not working

Here's my code
override func viewDidLoad() {
super.viewDidLoad()
let button1 = UIButton(frame: CGRect(x: 50, y: 50, width: 30, height: 30))
button1.setTitle("hi", for: .normal)
button1.setTitleColor(.blue, for: .normal)
button1.setTitleColor(.black, for: .highlighted)
button1.addTarget(self, action: #selector(self.barItem2Clicked(sender:)), for: .touchUpInside)
button1.backgroundColor=UIColor.red
let barButton1 = UIBarButtonItem(customView: button1)
toolBar1.items?.append(barButton1)
}
method barItem2Clicked :
func barItem2Clicked(sender :Any?) {
NSLog("hello")
}
I wanted to use UIButton add to UIToolBar, but the action of button1 can not be called, and the Highlighted effect is not shown too.
I clicked the button1 I just added, but the method barItem2Clicked never called.
Did I missed something?
Thanks
Please make sure that the toolBar1 is connected
I just tried with your code and it seems to be working.

Stuck with adding target to button programmatically

I've created a UIButton and I want it to print some message when it's pressed.
So I did something like this:
In loadView()
button.addTarget(self, action: #selector(ViewController.pressButton(button:)), for: .touchUpInside)
A method:
func pressButton(button: UIButton) {
NSLog("pressed!")
}
But nothing happens when I click the button.
Add the button code in your viewDidLoad and it will work for you:
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = UIColor.gray
button.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
self.view.addSubview(button)
}
func pressButton(button: UIButton) {
NSLog("pressed!")
}
You don´t need to add ViewController.pressButton to selector, it´s enough with the function name.
Swift 4.x version:
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 0
button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside)
self.view.addSubview(button)
#objc func pressButton(_ button: UIButton) {
print("Button with tag: \(button.tag) clicked!")
}
Swift 5.1 version:
let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 100
button.addTarget(self, action: #selector(pressButton), for: .touchUpInside)
self.view.addSubview(button)
#objc func pressButton(button: UIButton) {
print("Button with tag: \(button.tag) clicked!")
}
try this in Swift3!
button.addTarget(self, action: #selector(self.pressButton(button:)), for: .touchUpInside)
#objc func pressButton(button: UIButton) { NSLog("pressed!") }
Use the following code.
button.addTarget(self, action: #selector(FirstViewController.cartButtonHandler), for: .touchUpInside)
Your class name corresponds to FirstViewController
And your selector corresponds to the following function
func cartButtonHandler() {
}
In swift 3 use this -
object?.addTarget(objectWhichHasMethod, action: #selector(classWhichHasMethod.yourMethod), for: someUIControlEvents)
For example(from my code) -
self.datePicker?.addTarget(self, action:#selector(InfoTableViewCell.datePickerValueChanged), for: .valueChanged)
Just give a : after method name if you want the sender as parameter.
You mention that the addTarget call is in loadView(). Is this in your custom subview, of some kind, or the viewController?
From your selector, it's targeting a method in your ViewController class, but if the target for this action is the view itself, then it would make sense that the action is not going through.
If you declare your button in a viewController, and in viewDidLoad add this target as above, then the message should be printed as you're looking for. I believe you are "targetting" the wrong class with your action.
let cancelButton = UIButton.init(frame: CGRect(x: popUpView.frame.size.width/2, y: popUpView.frame.size.height-20, width: 30, height: 30))
cancelButton.backgroundColor = UIColor.init(patternImage: UIImage(named: cancelImage)!)
cancelButton.addTarget(self, action: #selector(CommentsViewController.canceled), for:.touchUpInside)
Add the button code in override func viewDidLoad() method
Make sure your action handler tagged with #IBAction like this:
#IBAction func pressButton(button: UIButton) {
print("pressed!")
}
Then it will work!

Set button type

I am creating a button programatically and I would like to know how to set that button's UIButtonType.
This is how I am creating my button:
let headerPlusButon:UIButton = UIButton(frame: CGRectMake(5, tableView.frame.width - 30, 20, 20))
headerPlusButon.addTarget(self, action: "paymentAddButtonTapped", forControlEvents:.TouchUpInside)
There is no "setButtonTypeFor..." method like how you would change the title's text and obviously this doesn't work:
headerPlusButon.buttonType = UIButtonType.ContactAdd
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender:UIButton!)
{
println("Button tapped")
}
from swift 2 replace UIButton declaration with below line.
let button = UIButton(type: .System) as UIButton
Here is my code
let tutorialButton = UIButton.init(type: .infoDark)
tutorialButton.frame = CGRect(x: self.view.frame.size.width - 20, y: 42, width: 20, height: 20)
tutorialButton.addTarget(self, action: #selector(self.showTutorial), for: .touchUpInside)
view.addSubview(tutorialButton)
I hope it can help you!

Resources