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)
}
}
Related
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
}
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
}
I'm creating a custom button item for my navigation bar, and I want it to have the same effect as the button system item ( Slow fade out )
Here is my code :
var button_user : UIImage = UIImage(named:"user.png")!
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.setImage(UIImage(named: "user.png"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "user_clicked.png"), forState: UIControlState.Highlighted)
button.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 28, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
You should change UIButtonType.Custom to UIButtonType.System for that:
let button = UIButton(type: UIButtonType.System)
button.setImage(UIImage(named: "user.png"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "user_clicked.png"), forState: UIControlState.Highlighted)
button.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 28, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
Edit
Updated for Swift 2.0
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
}
});
}
OR
button.setShowsTouchWhenHighlighted(true)
Edit: You should use UIBarButtonItem instead of UIButton in the navigation bar. That will do.
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "backbutton"), style: UIBarButtonItemStyle.Plain, target: self, action: "buttonClicked:")
And also add the method
func buttonClicked(sender: AnyObject){
//Enter your code here
}
add more "images" for the UIControlState accordingly
I am trying to create a UIButton in a NSObject class. I get the error " Use of unresolved identifier view. I figured that it needs to have UIViewController for it to work.
is there a work around so that I create multiple buttons with just this on multiple view controllers. what am I missing?
func createButton () {
let button = UIButton();
button.setTitle("Add", forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.frame = CGRectMake(15, -50, 200, 100)
view.addSubview(button)
}
Declare method definition with parameter-argument in which you want to add button :
func createButton (view:UIView) {
let button = UIButton();
button.setTitle("Add", forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.frame = CGRectMake(15, -50, 200, 100)
view.addSubview(button)
}
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)