Swift add show action to button programmatically - ios

how can I add action to button programmatically. I need to add show action to buttons in mapView. thanks
let button = UIButton(type: UIButtonType.Custom) as UIButton

You can go for below code
`
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle("Click Me", for: .normal)
btn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
btn.tag = 1
self.view.addSubview(btn)
for action
#objc func buttonAction(sender: UIButton!) {
let btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
dismiss(animated: true, completion: nil)
}
}

let button = UIButton(type: UIButtonType.Custom) as UIButton
button.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
//then make a action method :
func action(sender:UIButton!) {
print("Button Clicked")
}

You need to add a Target to the button like Muhammad suggest
button.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
But also you need a method for that action
func action(sender: UIButton) {
// Do whatever you need when the button is pressed
}

For swift 5 users can do by this simple way
cell.followButton.tag = 10
cell.followButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
#objc func buttonAction(sender: UIButton!) {
let id = sender.tag
print(id)
}

in addition to the above, the new ios14 introduce
if #available(iOS 14.0, *) {
button.addAction(UIAction(title: "Click Me", handler: { _ in
print("Hi")
}), for: .touchUpInside)
} else {
// Fallback on earlier versions
}

override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton()
btn.frame = CGRectMake(10, 10, 50, 50)
btn.setTitle("btn", forState: .Normal)
btn.setTitleColor(UIColor.redColor(), forState: .Normal)
btn.backgroundColor = UIColor.greenColor()
btn.tag = 1
btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
self.view.addSubview(btn)
}

For Swift 4 use following:
button.addTarget(self, action: #selector(AwesomeController.coolFunc(_:)), for: .touchUpInside)
//later in your AswesomeController
#IBAction func coolFunc(_ sender:UIButton!) {
// do cool stuff here
}

Related

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)

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!

How to change element title inside UITableViewCell?

I have a button on custom tableviewcell. I've been able add action to this button by add target like below code:
var playButton = cell.contentView.viewWithTag(5) as? UIButton
var sender : UIButton = UIButton()
playButton?.addTarget(self, action: "playPost:", forControlEvents: UIControlEvents.TouchUpInside)
playButton?.layer.setValue(object["previewUrl"] as? String, forKey: "songUrl")
playButton?.layer.setValue(indexPath.row, forKey: "index")
But, how can I change it's title whenever I clicked this button?
If your function is playPost(), you could change the value passed in (which is the sender of the function, by default) like this:
func playPost(sender: UIButton) {
sender.setTitle("New title", forState: UIControlState.Normal);
}
You can Change UIButton title by using setTitle Method
Example
var button = UIButton(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Start", forState: UIControlState.Normal)
button.addTarget(self, action: "pressButton:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
func pressButton(sender:UIButton)
{
if sender.titleLabel?.text == "Start"
{
sender.setTitle("Stop", forState: UIControlState.Normal)
}
else
{
sender.setTitle("Start", forState: UIControlState.Normal)
}
}

First UIButton fires another UIbutton event of same view

i have create two UIButton in swift and added action programmatically. When i try to click on the first button both button action are fired. But when i click on the second button none of the events are firing.
var btnSort = UIButton(frame: CGRectMake(2, 74, 140, 26))
btnSort.setTitle("SORT", forState: UIControlState.Normal)
btnSort.backgroundColor = UIColor.grayColor()
btnSort.tag=10
btnSort.addTarget(self, action: Selector("showSortTbl:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnSort)
var btnFilter = UIButton(frame: CGRectMake(140+16+2, 74, 140, 26))
btnFilter.backgroundColor = UIColor.redColor()
btnFilter.tag=11
btnFilter.setTitle("FILTER", forState: UIControlState.Normal)
btnSort.addTarget(self, action: Selector("showFilterTbl:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnFilter)
func showSortTbl(sender: UIButton){
var btnSendTag :UIButton = sender
if(btnSendTag.tag == 10){
println("show sort")
}
}
func showFilterTbl(sender: UIButton){
var btnSendTag :UIButton = sender
if(btnSendTag.tag == 11){
println("show filter")
}
}
Change this line
btnSort.addTarget(self, action: Selector("showFilterTbl:"), forControlEvents: UIControlEvents.TouchUpInside)
to
btnFilter.addTarget(self, action: Selector("showFilterTbl:"), forControlEvents: UIControlEvents.TouchUpInside)

Keep UIButton Selected/Highlighted after touch

I'd like my button to remain highlighted after the user taps it. If the user taps the button again I'd like it to become de-selected/unhighlighted. I'm not sure how to go about doing this in swift. I'm currently setting the button highlight image and selected image to the same .png using interface builder.
When I run the app and tap the button, it changes to my highlight image for as long as my finger remains on the button.
Use below code
declare isHighLighted as instance variable
//write this in your class
var isHighLighted:Bool = false
override func viewDidLoad() {
let button = UIButton(type: .system)
button.setTitle("Your title", forState: UIControlState.Normal)
button.frame = CGRectMake(0, 0, 100, 44)
self.view.addSubview(button as UIView)
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
}
func buttonClicked(sender:UIButton)
{
dispatch_async(dispatch_get_main_queue(), {
if isHighLighted == false{
sender.highlighted = true;
isHighLighted = true
}else{
sender.highlighted = false;
isHighLighted = false
}
});
}
I would recomend to use selected state instead of highlighted the below code demonstarate with selected state
override func viewDidLoad() {
let button = UIButton(type: .system)
button.setTitle("Your title", forState: UIControlState.Normal)
button.frame = CGRectMake(0, 0, 100, 44)
self.view.addSubview(button as UIView)
//set normal image
button.setImage(normalImage, forState: UIControlState.Normal)
//set highlighted image
button.setImage(selectedImage, forState: UIControlState.Selected)
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
}
func buttonClicked(sender:UIButton)
{
sender.selected = !sender.selected;
}
func buttonPressed(_ sender: UIButton) {
// "button" is a property
if button.isSelected {
button.setImage(UIImage(named: "filled-heart"), for: .normal)
button.isSelected = false
}else {
button.setImage(UIImage(named: "empty-heart"), for: .selected)
button.isSelected = true
}
}
func highlightButton(button: UIButton) {
button.highlighted = true
}
#IBAction func touched(sender: UIButton) {
let timer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: self, selector: Selector("highlightButton(sender)"), userInfo: nil, repeats: true)
}
this one worked fine for me!
func buttonColorChanger(sender : UIButton ) {
if button.isSelected == false
{
button.backgroundColor = UIColor.purple
print("selected")
button.setTitle("selected", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.isSelected = true
}else{
button.backgroundColor = UIColor.white
print("unselected")
button.isSelected = false
}
}
Swift 5:
#IBAction func toggleButton(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}

Resources