Stuck with adding target to button programmatically - ios

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!

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

Change Color of Programmatically Created Button when Pressed

I'm using a function to create multiple buttons for my game.
func createButton() {
let button = UIButton()
button.setTitle("", for: .normal)
button.frame = CGRect(x:15, y: 50, width: 200, height:100)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
button.addTarget(self, action: Selector(("buttonPressed:")), for:
.touchUpInside)
}
I call this function once for testing in viewDidLoad function, but I don't know what code I should put into my buttonPressed() function for the color of my button to change? I tried doing
self.backgroundColor = UIColor.blue
but that didn't work. I also tried using UIButton and button instead of self, but both of those didn't work either. What should I do?
Your code isn't clean Swift 4 code. Here's how to do this:
Create your button like you are, but change Selector to #selector:
func createButton() {
let button = UIButton()
button.setTitle("", for: .normal)
button.frame = CGRect(x:15, y: 50, width: 200, height:100)
button.backgroundColor = UIColor.red
self.view.addSubview(button)
button.addTarget(self, action: #selector((buttonPressed)), for: .touchUpInside)
}
Use the sender that is automatically added:
#objc func buttonPressed(sender: UIButton) {
sender.backgroundColor = UIColor.blue
}
Additionally may I offer a few suggestions?
Check the background color before changing it. No sense in needlessly changing a button that is already blue.
Since you aren't setting the title to your button, set the tag property (you can even add this as a parameter to createButton). This way you can know which button was tapped.
Just make the button an instance property.
let changingButton = UIButton()
func createButton() {
changingButton.backgroundColor = UIColor.red
changingButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
changingButton.backgroundColor = UIColor.blue
}

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.

How to set a listener function for a button defined programatically in swift 3

I am trying to set a listener function for my button but I keep getting error . Here is how've done it :
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Create the BackGround
self.view.backgroundColor = UIColor.black
let startButton = UIButton()
startButton.setTitle( " start ", for: UIControlState.normal)
startButton.setTitleColor(UIColor.blue, for: UIControlState.normal)
startButton.frame = CGRect(x: 10, y:40 , width: 250, height: 25)
self.view.addSubview(startButton)
startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)
}
func buttonPressed(sender: UIButton!) {
print("hello")
}
}
Does any one knows where am I making the mistake ? :)
You were close. Just replace
startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)
with this:
startButton.addTarget(self, action: #selector(ViewController.buttonPressed(sender:)) , for: .touchUpInside)

Swift3: Add button with code

Im reading Apples swift (iOS) documentation but its written for Swift 2 and i use Swift 3. I want to add a button programmatically but its seems there is a change and I can't find how to fix it.
Here is the Code for the Swift 2 example:
import UIKit
class RatingControl: UIView {
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Buttons
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red()
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
addSubview(button)
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: 240, height: 44)
}
// MARK: Button Action
func ratingButtonTapped(button: UIButton){
print("Button pressed")
}
}
The only change i made after the 'fix-it' showed the error is this in the selector:
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(button:)), for: .touchDown)
This should have printed "Button pressed" but it doesn't. Any help?
My code:
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)
override var intrinsicContentSize : CGSize {
//override func intrinsicContentSize() -> CGSize {
//...
return CGSize(width: 240, height: 44)
}
// MARK: Button Action
func ratingButtonTapped(_ button: UIButton) {
print("Button pressed 👍")
}
Try something like this. I haven't tested but it should work:
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = UIColor.red
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside)
addSubview(button)
func ratingButtonTapped() {
print("Button pressed")
}
Found the solution. For some reason the:
func ratingButtonTapped(button: UIButton)
needs an "_" before button. So it should be :
func ratingButtonTapped(_ button: UIButton)
And the other part of the code must be :
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), for: .touchDown)
Thanks for helping :) Your method may be correct also but thats the one Apple wants it.

Resources