Attach parameter to button.addTarget action in Swift
You cannot pass custom parameters in addTarget:
.One alternative is set the tag
property of button and do work based on the tag.
button.tag = 5
button.addTarget(self, action: "buttonClicked:",
forControlEvents: UIControlEvents.TouchUpInside)
Or for Swift 2.2 and greater:
button.tag = 5
button.addTarget(self,action:#selector(buttonClicked),
forControlEvents:.TouchUpInside)
Now do logic based on tag
property
@objc func buttonClicked(sender:UIButton)
{
if(sender.tag == 5){
var abc = "argOne" //Do something for tag 5
}
print("hello")
}
Passing parameters to addTarget:action:forControlEvents
action:@selector(switchToNewsDetails:)
You do not pass parameters to switchToNewsDetails:
method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:
with no parameters
action:@selector(switchToNewsDetails)
with 1 parameter indicating the control that sends the message
action:@selector(switchToNewsDetails:)
With 2 parameters indicating the control that sends the message and the event that triggered the message:
action:@selector(switchToNewsDetails:event:)
It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:
- set a tag property to each button equal to required index
in
switchToNewsDetails:
method you can obtain that index and open appropriate deatails:- (void)switchToNewsDetails:(UIButton*)sender{
[self openDetails:sender.tag];
// Or place opening logic right here
}
Pass multiple parameters to addTarget
May be you can do something like this
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:indexPath) as! CartTableViewCell
cell.buyButton.tag = (indexPath.section*100)+indexPath.row
cell.buyButton.addTarget(self, action: "btnBuy_Click:", forControlEvents: .TouchUpInside)
}
func btnBuy_Click(sender: UIButton) {
//Perform actions here
let section = sender.tag / 100
let row = sender.tag % 100
let indexPath = NSIndexPath(forRow: row, inSection: section)
self.buyButton(indexPath, 2, 3 ,4 , 5, 6)
}
Create tag value according to you'r requirement and maintaint it's integrity too.
How to pass a Parameter to the addTarget method of button in swift
If the title to be passed is button's title, then you can simply do this :-
@objc func buttonPressed(sender: UIButton){
let title = sender.title(for: .normal)
}
And if it is some other data in section, you can use tags on your buttons, and setting them to indexPath.row :-
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.buttonView.tag = indexPath.row
}
And in your Button's action, access button's tag
@objc func buttonPressed(sender: UIButton){
let objectIndex = sender.tag
let object = yourArray[objectIndex]
let title = object.title
}
How to add a function with parameter in addTarget of UIButton in swift 5?
I don't believe it is possible to pass custom parameters to a #selector
, as stated here,
Action methods must have a conventional signature. The UIKit framework permits some variation of signature, but both platforms accept action methods with a signature similar to the following:
meaning you method can at least have one of the following signatures:
@objc func buttonActionSkip(sender: UIButton)
@objc func buttonActionSkip(sender: UIButton, for event: UIEvent)
You can however, change the sender type. A possible solution for your problem could be extending the UIButton class adding a name
property:
class MyMainSkipButton: UIButton {
var name: String = ""
}
Then on your code:
//button initialization
let MainSkipButton = MyMainSkipButton(type: .custom)
MainSkipButton.frame = CGRect(x: 50 , y: 48, width: 47.0, height: 24.0)
MainSkipButton.backgroundColor = .blue
MainSkipButton.layer.cornerRadius = 10
MainSkipButton.layer.borderWidth = 1
MainSkipButton.layer.borderColor = UIColor.white.cgColor
MainSkipButton.setTitle(NSLocalizedString("Skip", comment: "Button"), for: .normal)
MainSkipButton.setTitleColor(.white, for: .normal)
MainSkipButton.name = "what ever the name is"
MainSkipButton.addTarget(self, action: #selector(buttonActionSkip(sender:)), for: .touchUpInside)
self.view.addSubview(MainSkipButton)
//function initialization
@objc func buttonActionSkip(sender: MyMainSkipButton) {
print("Receive parameter string is\(sender.name)")
sender.isHidden = true
}
Add target to Button in Swift
Matt is right!! your approach is totally wrong here. Please try to modify your approach.
Your approach should be something like this:
override func viewDidLoad() {
super.viewDidLoad()
//Set Target to your button only once.
editButton.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)
}
@objc func didTapEditButton() {
//Add IF conditions according to what your button should do in different cases here.
if user.uid == UserApi.shared.CURRENT_USER_ID {
goToSettings()
}else {
if user.isFollowing! == true {
setupUnfollowButton()
} else {
setupFollowButton()
}
}
}
func setupFollowButton() {
//Make the check to see what state your button is currently in by checking if the title of the button is "Follow" or "Unfollow"
if editButton.titleLabel?.text == "Unfollow"{
editButton.layer.borderWidth = 1
editButton.layer.borderColor = UIColor.lightGray.cgColor
editButton.layer.cornerRadius = 5
editButton.clipsToBounds = true
editButton.setTitleColor(UIColor.white, for: .normal)
editButton.backgroundColor = UIColor(red: 1 / 255, green: 84 / 255, blue: 147 / 255, alpha: 1.0)
editButton.setTitle("Follow", for: UIControl.State.normal)
followAction()
}
}
func setupUnfollowButton() {
//Do the same here for the other state.
if editButton.titleLabel?.text == "Follow"{
editButton.layer.borderWidth = 1
editButton.layer.borderColor = UIColor.lightGray.cgColor
editButton.layer.cornerRadius = 5
editButton.clipsToBounds = true
editButton.setTitleColor(UIColor.black, for: .normal)
editButton.backgroundColor = UIColor.white
editButton.setTitle("Unfollow", for: UIControl.State.normal)
unFollowAction()
}
}
func followAction() {
print("Button wurde gedrückt")
if user?.isFollowing == false {
FollowApi.shared.followAction(withUser: user!.uid!)
setupUnfollowButton()
user?.isFollowing = true
}
}
func unFollowAction() {
print("Button wurde gedrückt")
if user?.isFollowing == true {
FollowApi.shared.unfollowAction(withUser: user!.uid!)
setupFollowButton()
user?.isFollowing = false
}
}
Can I attach parameters (not sender) to uiButton.addTarget in Swift 4
There are many ways to do this. I'm pointing two possible ways.
1. You can subclass UIButton and have the parameters to it.
class MyButton: UIButton{
var myParam1: String?
var myParam2: String?
}
Create custom tableview cell and handle the button call inside
import UIKit
class MyCell: UITableViewCell{
@IBOutlet weak var myButton: UIButton!
@IBOutlet weak var anotherButton: UIButton!
func setup(model: YourDataModel){
myButton.addTarget(self, action:#selector(self.didSelect(_ :), for: .touchUpInside)
anotherButton.addTarget(self, action: #selector(self.didSelect(_ :)), for: .touchUpInside)
}
@objc func didSelect(_ sender: UIButton){
switch sender {
case myButton:
print("my button clicked")
case anotherButton:
print("anotherButton clicked")
default:
break
}
}
}
Related Topics
Examples of Delegates in Swift
Swift Protocol With "Where Self" Clause
What's the Difference Between "As", "As!", and "As"
Printing a Variable Memory Address in Swift
How to Encode a String to Base64 in Swift
How to Reset the App Between Tests in Swift Xctest Ui
Is This Response from the Compiler Valid
Multi-Touch Gesture in Sprite Kit
How to Enumerate an Enum With String Type
Swift - Resolving a Math Operation in a String
The "++" and "--" Operators Have Been Deprecated Xcode 7.3
Changing the Status Bar Color For Specific Viewcontrollers Using Swift in Ios8
What Is Geometry Reader in Swiftui