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")
}
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
}
}
UIButton.addTarget with swift 3 and local function
Here you need to use objc_setAssociatedObject
Add extension in project:-
extension UIButton {
private struct AssociatedKeys {
static var DescriptiveName = "KeyValue"
}
@IBInspectable var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
)
}
}
}
}
How to use :-
//let newI = i.replacingOccurrences(of: "GPS30", with: "")
button?.descriptiveName = "stringData" //newI use here
How to get parameter :-
func buttonAction(sender: UIButton!) {
print(sender.descriptiveName)
}
UIControl addTarget(_:action:for:) Method in Swift 3.2
Yes, they changed it from a String
where it was simply a runtime error if you mistyped a method name to a #selector
that forces a compile time check for the method. They're just trying to find your errors earlier.
However, if awesomeMethod is NOT in ClassA, let's say it's in ClassB,
then the compiler complains and I am forced to specify the class name
in the action.
No, you can specify an @objc
protocol
that implements the method:
@objc protocol AwesomeProtocol {
func awesomeMethod()
}
Then, even if your class doesn't implement that method, you can specify:
awesomeBtn.addTarget(nil, action: #selector(AwesomeProtocol.awesomeMethod), for: .touchUpInside)
Note: It doesn't seem to be necessary for anyone to adopt that protocol. The button searches up the responder chain and uses the first matching method that it finds. Although, you should adopt the protocol by any class that implements awesomeMethod
so that Swift can detect errors in the method signature at compile time.
Swift 3 UIButton addTarget not working
It works fine when i try your code with one change as i don't have backView. So replaced
backView.addSubview(backButton)
with
self.view.addSubview(backButton)
I can see the log present in pressBackButton function on console on pressing the button. Make sure your console view is not disabled. shift+command+C shows the console view.
Related Topics
How to Disable Control Center in iOS 7 Programmatically and If Not, What Are Alternatives
Implement Dark Mode Switch in Swiftui App
The App References Non-Public Selector in Id (Facebook Sdk iOS)
How to Load Resource in Cocoapods Resource_Bundle
Xcode 6: No Frameworks Folder in Project Navigator
Send Programmatically Sms on Jailbreak Device
How to Round Corners of Uiimage with Hexagon Mask
Cocoa-Touch: How to See If Two Nsdates Are in the Same Day
Uibutton That Resizes to Fit Its Titlelabel
In Call Status Bar (Unable to Satisfy Constraints)
How to Change Uitableviewrowaction Title Color
How to Use Keychain for Saving Password Like Generickeychain Sample Code
Does Swift Support Implicit Conversion
The Supportedinterfaceorientations Method Doesn't Override Any Method from Its Superclass
The Operation Couldn't Be Completed. (Com.Facebook.Sdk Error 2.) iOS6
How to Add Image in Uitableviewrowaction
Custom Font Sizing in Xcode 6 Size Classes Not Working Properly with Custom Fonts