// Funtion Method
func TappedButtonCallFunction()
{
btnSaveFilterWorkLog(UIButton.init())
}
// Button Action
#IBAction func btnSaveFilterWorkLog(_ sender: UIButton) {
print("Button Tapped")
}
// Button Tapped
The proper way is to use sendAction method from the UIControl class.
You call this method when you want the control to perform the actions associated with the specified events.
In our case:
button.sendActions(for: .touchUpOutside)
Just put ? in function declaration behind uibutton object. Now you can pass nil value in argument but make sure you are not using sender anywhere
And do not worry your button tap event will not effected it will work same
//Calling
btnSaveFilterWorkLog(nil)
// Button Action
#IBAction func btnSaveFilterWorkLog(_ sender: UIButton?) {
print("Button Tapped")
}
also you can create programmatically method
for example:
button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)
and method selector:
#objc
func buttonAction() {
print("some")
}
don't forget to put #objc
import UIKit
class ActionSheetViewController: UIViewController {
#IBOutlet weak var closeButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
closeButton.addTarget(self, action: #selector(dismissActionSheet), for: .touchUpInside)
}
#objc func dismissActionSheet() {
// some code goes here ie:
dismiss(animated: true, completion: nil)
}
}
Above works perfectly in Swift5.
Related
Is there any way to use addTarget on something other than self (which seems to be the most common use case)?
Yes, you can use a target other than self. The most common use is to call addTarget with self where self is a reference to the viewController that the adds the UIControl to its view hierarchy. But you aren't required to use it that way. The target is merely a reference to an object, so you can pass it a reference to any object you want. The action is a Selector which needs to be defined as an instance method on the class of that object, and that method must be available to Objective-C (marked with #objc or #IBAction) and it must take either no parameters, just the sender, or the sender and the event.
You can also pass nil as the target, which tells iOS to search up the responder chain for the action method.
Here's a little standalone example:
import UIKit
class Foo {
#objc func buttonClicked() {
print("clicked")
}
}
class ViewController: UIViewController {
let foo = Foo()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 50, y: 200, width: 100, height: 30))
button.setTitle("Press me", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(foo, action: #selector(Foo.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)
}
}
You can certainly set up some other object to receive control actions. Consider the following view controller:
First, define a class who's job is to respond to button tap actions:
#objc class ButtonTarget: NSObject {
#IBAction func buttonAction(_ sender: Any) {
print("In \(#function)")
}
}
Now define a view controller that creates a ButtonTarget object
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
lazy var buttonTarget = ButtonTarget() //Give the ViewController a `ButtonTarget`
override func viewDidLoad() {
super.viewDidLoad()
//Add a taret/action to the button that invokes the method `buttonAction(_:)`
button.addTarget(
buttonTarget,
action: #selector(ButtonTarget.buttonAction(_:)),
for: .touchUpInside)
}
}
I have a simple view V and view controller C. The controller calls a separate class X that build a webview and a button to close the webview.
I instantiate class X (with a reference to view V) then call a method to attach both items (webview and items).
When i call the button addTarget method, it does not work. I want it to execute the closeAll method of the X class and not the closeAll method of the C controller.
I have tried hundreds of variants.
Here is (parts of) the code in C controller:
let parentView:UIView
...
#objc func closeAll() {
print("Close webview, object")
}
and this in X class:
...
let transparentButton = UIButton(frame: frame)
transparentButton.backgroundColor = UIColor.black.withAlphaComponent(self.overlayTransparency)
transparentButton.setTitle("", for: .normal)
transparentButton.alpha = 0.5
transparentButton.isUserInteractionEnabled = true
transparentButton.addTarget(self, action:#selector("closeAll"), for: .touchUpInside)
parentView.addSubview(transparentButton)
I have this in my C controller and it get called on click:
#objc func closeAll() {
print("Close webview, main")
}
Change self to instance of a class that you want it's method to be triggered
You can insert either of these into your class:
override func viewDidLoad() {
super.viewDidLoad()
transparentButton.addTarget(self, action:#selector(closeAll), for: .UIControlEvents.valueChanged)
}
func closeAll(sender:AnyObject) {
// your code
}
OR
#IBOutlet var btnStartJob: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btnStartJob.addTarget(self, action: #selector(closeAll), for: .touchUpInside)
}
func closeAll(_ sender : UIButton) {
// your code
}
I want to be able to call function start within function use without hitting the action button for start. I know simple thing to do is just put print("a") in use. But I am using this as a simple example because I have a more complex problem in mind.
#IBAction func start(_ sender: Any) {
print("a")}
fun use() {
}
viewdidload() {
use()
}
Consider refactoring your functions. Instead of putting the button action code directly inside of the #IBAction function, put it in a separate function. This way, you can call this code from multiple places.
Here is one solution:
#IBAction func start(_ sender: Any) {
startAction()
}
func startAction() {
print("a")
}
func use() {
startAction()
// anything else
}
override func viewDidLoad() {
use()
}
Create an IBOutlet for your button:
#IBOutlet weak var button: UIButton!
Then simply, use this code to trigger its action:
button.sendActions(for: .touchUpInside)
I have an IBAction connected to a button, and I wanted to know if there is any way to run that function even if the button is not being pressed. This is what I tried...
Note: I am using swift for this project.
//I get an error when I type this code?
self.buttonPressed()
#IBAction func buttonPressed(sender: AnyObject) {
print("Called Action")
}
Make your sender argument optional and pass nil to ButtonPressed.
self.ButtonPressed( nil )
#IBAction func ButtonPressed( sender: AnyObject? ) {
println("Called Action")
}
One way would be to link your button up to its respective interface builder button and pass it into your function when you call it.
#IBOutlet weak var yourButton: UIButton!
self.buttonPressed(yourButton)
#IBAction func buttonPressed(sender: AnyObject) {
print("Called Action")
}
Alternatively, define your function like so, then you'll be able to call your method the same way as you did before:
#IBAction func buttonPressed(sender: AnyObject? = nil) {
print("Called Action")
}
// Call your method like this
self.buttonPressed()
// or this
self.buttonPressed(sender: nil)
Your ButtonPressed function needs an argument sender and yet you're not passing any when you call it. However, if you're doing this programatically, then you obviously don't have a sender.
Two ways to get around this:
Make the sender parameter an optional (AnyObject? instead of AnyObject) and invoke self.ButtonPress(nil). I just tried this and it works.
Put all the button press function in a separate function, e.g., performButtonPress(). Call it from inside the IBAction outlet, and if you want to press the button programatically, directly call performButtonPress().
Call a button action using the following format: Swift 3
#IBAction func buttonSelected(_ sender: UIButton) {
print("Butten clicked")
}
To call the button action:
let button = UIButton()
self.buttonSelected(button)
You need to use "self" as "sender", example:
self.buttonPressed (sender: self)
or a simpler version
buttonPressed (sender: self)
Both tested in Swift 3
lazy var Button : UIBarButtonItem = {
let barButtonItem = UIBarButtonItem(title: "Button", style: .done, target: self, action: #selector(btnSelection))
return barButtonItem
}()
func btnSelection(){
// Code
}
// Now you can call self.btnSelection() whenever you want
I have 2 classes, the first class is named "store" where I create a button which calls a method: "storeSelected" located in the second class with the name ExploreViewController.
The method should print "done" and take me to another view controller.
Without the segue "done" is printed but when putting the segue code the app crashes.
The error is:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver (<Glam.ExploreViewController: 0x14ed3be20>) has no segue with identifier 'ok''
.........
// ExploreViewController Class
let _sharedMonitor: ExploreViewController = { ExploreViewController() }()
class ExploreViewController: UIViewController, UIScrollViewDelegate {
class func sharedMonitor() -> ExploreViewController {
return _sharedMonitor
}
func storeSelected(sender: UIButton) {
println("done") // it entered here and "done" is printed
self.performSegueWithIdentifier("ok", sender: self) //here is the problem
}
}
// another class named "Store"
// button is created
let monitor = ExploreViewController.sharedMonitor()
btn.addTarget(monitor, action: Selector("storeSelected:"), forControlEvents: UIControlEvents.TouchUpInside)
Assuming that you have a view controller where you create the Store object - you should pass the button action back to this view controller and add a segue from it to your desired destination.
Best practice is to use a protocol that delegates the buttons action back up to the viewController that it is contained in as below.
Store.swift
protocol StoreDelegate: NSObject {
func didPressButton(button: UIButton)
}
class Store: UIView {
weak var delegate: StoreDelegate!
override init(frame: CGRect) {
super.init(frame: frame)
var button = UIButton()
button.setTitle(
"button",
forState: .Normal
)
button.addTarget(
self,
action: "buttonPress:",
forControlEvents: .TouchUpInside
)
self.addSubview(button)
}
func buttonPress(button: UIButton) {
delegate.didPressButton(button)
}
}
ViewController.swift
class ViewController: UIViewController, StoreDelegate {
override func viewDidLoad() {
super.viewDidLoad()
addStoreObj()
}
func addStoreObj() {
var store = Store()
store.delegate = self // IMPORTANT
self.view.addSubview(store)
}
func didPressButton(button: UIButton) {
self.performSegueWithIdentifier(
"ok",
sender: nil
)
}
}
This code is untested, but I hope you get the idea - your Store object delegates the button press activity back to its containing ViewController and then the ViewController carries out the segue that you have attached to it in the Storyboard.