I just want to write one or two lines of code on button click like
print("Button Clicked")
for this i dont want to create a seperate function and call via selector
as
action: #selector(BtnKlkFnc(_:))
I want to simplify like
action: { action in print("Button Clicked")}
I also tried
#selector({print("Button Clicked")})
Can anyone help me to simplify this
Am new to stackoverflow and do not have enough reputations yet, So kindly vote for my question up, so i can vote for your ans
Short answer: You can't do that. Button actions are part of the target/action mechanism built into Cocoa/Cocoa touch. It's based on selectors, and you must create a named method and use it's selector. You can't use a Swift closure as a button action.
EDIT:
Note that it is possible to create a custom subclass of UIButton that has a closure property and invokes that closure when the button is tapped. What you'd do is to make the button's init method set itself up as the target of a touchUpInside event and invoke a method of the button that in turn invokes your closure (after making sure the closure property isn't nil.)
EDIT #2:
Note that it is pretty straightforward to create a custom subclass of UIButton that sets itself up as the target for button presses and keeps a closure.
Here is a sample implementation:
class ClosureButton: UIButton {
var buttonClosure: ((UIButton) -> Void)?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addTarget(self, action: #selector(handleTap(_:)), for: .touchUpInside)
}
#objc func handleTap(_ sender: UIButton) {
if let buttonClosure = buttonClosure {
buttonClosure(sender)
} else {
print("No button closure defined")
return
}
}
}
And in your view controller:
override func viewDidLoad() {
super.viewDidLoad()
button.buttonClosure = { _ in
print("You tapped the button")
}
}
Related
We can initialize a new UIButton this way:
// myAction is a var of type UIAction
let btn = UIButton(primaryAction: myAction)
So I'm thinking cool, I can subclass this and stop using target-action. But here's the problem, Xcode can't seem to recognize the primaryAction initializer.
class Button: UIButton {
init(type: String, action: UIAction) {
super.init(primaryAction: action) // Error "Must call a designated initializer of the superclass 'UIButton'"
}
}
So it's not a designated initializer. How can I access this primaryAction property inside a UIButton subclass?
Because you can't initialize a superclass within a custom initializer with one of its convenience initializers, you have to perform the tasks of that convenience init manually. So after you've initialized the superclass with one of its designated inits:
class Button: UIButton {
init(type: String, action: UIAction) {
super.init(frame: .zero)
// register the action for the primaryActionTriggered control event
// and set the title and image properties to the action’s title and image
}
}
And it's not as straightforward as changing the value of a single property.
You set up a control so that it sends an action message to a target
object by associating both target and action with one or more control
events. To do this, send addTarget(_:action:for:): to the control for
each Target-Action pair you want to specify.
https://developer.apple.com/documentation/uikit/uicontrol/event
I figured it out. We can use addAction instead of addTarget. Requires iOS 14+.
func addAction(_ action: UIAction, for controlEvents: UIControl.Event) is available on all subclass of UIControl. Meaning we no longer have to scatter targets and #objc func all over our code. Just add a UIAction to your control.
class Button: UIButton {
init(type: String, action: UIAction) {
super.init(frame: .zero)
addAction(action, for: .touchUpInside)
}
}
We want Lyft button touch event because I am working in analytics, so, I need how many people choose Lyft but I can't put UIView click event. I try below code.
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction))
cell.lyftButton.addGestureRecognizer(gesture)
How can i achieve this?
You can directly assign a selector method to lyftButton e.g
lyftButton.addTarget(self, action: #selector(lyftButtonAction(_:)), for: .touchUpInside)
#objc
func lyftButtonAction(_sender: UIButton) {
//Do your action
}
To retrieve the LyftButton, you'll need to fetch the button inside the Lyft view, after retrieving it, I tried to add another target to it which was your 'checkAction' method, but for some reason it is not being called. One workaround solution is:
On Auto Layout, created a transparent button on top of the Lyft Button View, let's callet it 'Transparent Lyft Button': Example (I've embeded in another view because it was on a stackView);
On the code, retrieved the button with the above method, held it in a variable, let's call it 'requestLyftButton' and disabled it.
Created an IBAction for the 'Transparent Lyft Button' that triggers the method 'self.checkAction' that you've created and also calls requestLyftButton.sendActions(for: .touchUpInside), which triggers the original Lyft SDK action.
To Retrieve Lyft UIButton:
#IBOutlet weak var lyftButton: LyftButton!
#IBOutlet weak var transparentLyftButton: UIButton!
var requestLyftButton: UIButton?
func retrieveLyftButton(in view: UIView) {
for view in view.subviews {
if let lyftBtn = view as? UIButton {
lyftBtn.isEnabled = false
requestLyftButton = lyftBtn
} else {
retrieveLyftBtn(in: view)
}
}
}
transparentLyftButton IBAction to trigger your method + lyft sdk original action:
#IBAction func requestLyft(_ sender: UIButton) {
if let lyftBtn = requestLyftButton {
checkAction() // Your method
lyftBtn.sendActions(for: .touchUpInside)
}
}
I hope that you can understand what was done, if you have any questions, just let me know.
I have created a custom view that is to be used as a radio button with images and text. I need to be able to load the saved selection when the controller loads. I set my listeners this way:
for button in genderButtons {
button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(genderTapped(_:))))
}
#objc private func genderTapped(_ sender: UITapGestureRecognizer) {
for button in genderButtons {
button.select(sender.view! == button) // Toggles the button to display selected/deslected state.
...
}
}
The problem is that I can't find a way to tell the view to select. I tried making the gesture recognizer and object, but it doesn't have any methods I can use to trigger it. The 'buttons' aren't actually buttons, they're views, so I can't send an action event.
How can I select the correct button with code?
Just call genderTapped directly, handing it the gesture recognizer already attached to the desired "button".
For example, if thisGenderButton is the one you want to "tap", say:
if let tap = thisGenderButton.gestureRecognizers?[0] as? UITapGestureRecognizer {
genderTapped(tap)
}
You can add this method in your customView like this,
Class CustomView: UIView {
public func select(_ value: Bool) {
self.backgroundColor = value ? .green: .red
}
}
and then in below method you can call select for the tapped view.
#objc private func genderTapped(_ sender: UITapGestureRecognizer) {
(sender.view as? CustomView)?.select(true)
}
I created a UISwitch on storyboard and tried to drag it to controller to create an action but there were only Insert Outlet / Insert Outlet Collection 2 options available? Why did this happen and how can I create action for UISwitch? I am using Xcode8.1
PS: The UISwitch was added on a container view
When "ctrl" + drag, you should see something like:
You should choose "Action" and let the event -which is by default- "Value Changed".
However, if you can't see this (and I assume you should, or there is somehow a problem), you can add an event programmatically to the switch outlet:
In viewDidLoad() method, you need to add:
override func viewDidLoad() {
// ...
mySwitch.addTarget(self, action: #selector(mySwitchTapped), for: .valueChanged)
// ...
}
mySwitchTapped(mySwitch: UISwitch) method:
func mySwitchTapped(mySwitch: UISwitch) {
if mySwitch.isOn {
} else {
}
}
I try figure out why self point to the GameViewController instead of Answer
GameViewController.swift
class GameViewController: UIViewController {
var gameplay = QuestionsController(colors: colors)
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(gameplay.answersController.answers[0].button)
}
func didPressAnswerButton(sender: UIButton!) {
sender.setTitle("Im from GameViewController class", forState: .Normal)
}
}
QuestionsController.swift
class QuestionsController {
var question: Question
var answersController: AnswersController
}
AnswersController.swift
class AnswersController {
var answers = [Answer]()
func prepareAnswers() {
let answer = Answer()
answers.append(answer)
}
}
Answer.swift
class Answer{
let button: UIButton
func prepareButton() {
let answerButton = AnswerButton(type: .System)
answerButton.addTarget(self, action: "didPressAnswerButton:", forControlEvents: .TouchUpInside)
button = answerButton
}
func didPressAnswerButton(sender: UIButton!) {
sender.setTitle("Im from Answer class", forState: .Normal)
}
}
addTarget:action:forControlEvents: tells the control (answerButton in this case) what method to call, and what object to call it on, when the user taps the button. Looking at your code in more detail:
answerButton.addTarget(self, action: "didPressAnswerButton:", forControlEvents: .TouchUpInside)
When the user taps a button, the TouchUpInside event fires on the answerButton, and when that happens we want to invoke a method didPressAnswerButton: on an Answer object
So, we need to tell answerButton what do do when this TouchUpEvent fires. You do this calling the addTarget:action:forControlEvents method on the answerButton
The self argument tells the answerButton what object to notify about the event: it is the target. In this context, self is an Answer object.
The "didPressAnswerButton:" argument indicates what method the answerButton should call in response to the tap event: this is the action
This is the target-action mechanism of Objective-C/Cocoa. It's a very common pattern, it's worth it to read the linked documentation to learn a bit more about how it works. The key is that this is based on Objective-C* message passing: in the code above, "didPressAnswerButton:" indicates a selector, which when paired with a target (self), tells the answerButton how to send a "message" to the target when the user taps the button.
Also, note that when you are editing a storyboard and ctrl-drag from a button to your view controller and select a method, you are also setting up a target/action using this same mechanism. You select the target object by dragging to the view controller icon (or some other icon), and then you pick the action/selector when clicking on a method name in the popup.
* Target-Action was originally designed for Objective-C, but for the common case of implementing a view controller, you can assume Swift works the same way. Just note when reading documentation that Swift uses simple strings for actions, whereas Objective-C uses #selector(...).