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)
}
}
Related
// 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.
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
}
In the creation of a swift iOS app, I needed to handle the event of a UIButton press outside of the parent view controller, so I created a (very simple) protocol to delegate that responsibility to a different class:
import UIKit
protocol MyButtonProtocol {
func buttonPressed(sender: UIButton)
}
However, when I try to addTarget to a UIButton with that protocol, I get this error: Cannot convert value of type 'MyButtonProtocol' to expected argument type 'AnyObject?'. Shouldn't anything be able to be converted to AnyObject?? Here is my main code:
import UIKit
class MyView: UIView {
var delegate: MyButtonProtocol
var button: UIButton
init(delegate: MyButtonProtocol) {
self.delegate = delegate
button = UIButton()
//... formatting ...
super.init(frame: CGRect())
button.addTarget(delegate, action: "buttonPressed:", forControlEvents: .TouchUpInside)
addSubview(button)
//... more formatting ...
}
}
Thanks in advance.
AnyObject is the protocol to which all classes conform.
To define a protocol which can only adopted by classes, add
: class to the definition:
protocol MyButtonProtocol : class {
func buttonPressed(sender: UIButton)
}
Without that modification,
var delegate: MyButtonProtocol
can be a struct or enum type and that is not convertible to AnyObject.
//i hope it will work
import UIKit
class MyView: UIView {
var delegate: MyButtonProtocol
var button: UIButton
init(delegate: MyButtonProtocol) {
self.delegate = delegate
button = UIButton()
//... formatting ...
super.init(frame: CGRect())
button.addTarget(delegate, action: Selector("buttonPressed:") forControlEvents: .TouchUpInside)
addSubview(button)
//... more formatting ...
}
}
class Test: NSObject {
init(mainView:UIView){
super.init()
var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
button.setTitle("Test", forState: UIControlState.Normal)
button.backgroundColor = UIColor.whiteColor()
button.frame = CGRectMake(0, 0, 250, 40)
button.addTarget(self, action: "doSomething", forControlEvents: UIControlEvents.TouchUpInside)
mainView.addSubview(button)
}
func doSomething(){
println("test")
}
}
in other class I try to doSomething() by clicking this button, but unsuccessfully my app crash...
var testvar = Test(view)
How to trigger this function by button pressed without app crash ?
It's a memory management issue. Your problem is that the Test instance you stored in the local variable testvar will be released after you left the method. The addTarget of UIButton method does not retain it's target, so there are no more strong references to the Test instance and it will be deallocated. If you tap the button the system tries to call doSomething on the now deallocated instance. Which leads to a crash.
You could store the instance in a instance variable of your UIViewController (or whatever object calls var testvar =).
e.g.:
class FirstViewController: UIViewController {
var testvar: Test!
override func viewDidLoad() {
super.viewDidLoad()
testvar = Test(mainView:self.view)
}
}
I am creating a UIButton in another file opposed to the main ViewController. I created this button
var newNoteButton = UIButton(frame: CGRectMake(5, 18, 152.5, 37))
newNoteButton.backgroundColor = UIColor.grayColor()
newNoteButton.addTarget(self, action: ("newNoteButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
newNoteButton.setTitle("New Note", forState: UIControlState.Normal)
newNoteButton.userInteractionEnabled = true
self.view.addSubview(newNoteButton)
with action
func newNoteButtonAction (sender: UIButton!){
println("New Note")
}
It is throwing the above error even though, if i copy and paste the same code into my ViewController, it doesn't flag me at all. Why is it doing this? It is meant to just print out the string "New Note" but something causes Thread 1 to queue.
Edit:
After a bit of reading, I have been able to reduce the amount of code to just this:
var newNoteButton = UIButton(frame: CGRectMake(5, 18, 152.5, 37))
newNoteButton.backgroundColor = UIColor.grayColor()
newNoteButton.addTarget(self, action: ("newNoteButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
and this:
func newNoteButtonAction (sender: UIButton!){
println("New Note")
}
I tried removing the action and the problem was still there. This exists within my textView class in a separate file. In my AppDelegate file, the Root View Controller is ViewController. If I move the button to ViewController, the issue does not present itself. The only code in my ViewController is this
import Foundation
import UIKit
class ViewController: UIViewController, UITextViewDelegate, UIScrollViewDelegate {
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
//Global Variables
var scrollView = UIScrollView()
override func viewDidLoad(){
super.viewDidLoad()
//Add textView
//let textViewRef = textView() Removed to test
//self.view.addSubview(textViewRef.view)
//Button Code
var newNoteButton = UIButton(frame: CGRectMake(5, 18, 152.5, 37))
newNoteButton.backgroundColor = UIColor.grayColor()
newNoteButton.addTarget(self, action: ("newNoteButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(newNoteButton)
}
func newNoteButtonAction (sender: UIButton!){
println("New Note")
}
}
I have tried messing about with conditionals and the semicolon in the action but that doesn't seem to affect it or help in any way. If you need any more information, please feel free to ask.
Edit 2
My other View Controller looks like this:
import Foundation
import UIKit
class textView: UIViewController {
//Globals
var newNoteButton = UIButton()
override func viewDidLoad()
newNoteButton = UIButton(frame: CGRectMake(5, 18, 152.5, 37))
newNoteButton.backgroundColor = UIColor.grayColor()
newNoteButton.addTarget(self, action: ("newNoteButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(newNoteButton)
}
func newNoteButtonAction (sender: UIButton!){
println("New Note")
}
}
Edit 3: I just noticed that this information might be a bit relevant. The error is on the class AppDelegate line in my delegate file.
I had the same problem and I received the same error that you. I wanted create a button in other class. I recommend you read my solution: How invoke a method in the method addTarget of the Button class when I create programmatically the button in a plain class in Swift . An abstract, you should inherit of the "UIClass" that you require. If you want to create a button, you should inherit of "UIButton" class. Then, you set the values of the attributes of this class instead of create a button.
FYI for anybody with this issue in the future, it can usually be debugged back to the retention of the button within the class you are adding the target to.
Try moving the declaration of the button or targeted class up to a class global to be cleaned up after the view is disposed of.
Example: In the instance listed above, declare the newNoteButton at the class level instead of inside the viewDidLoad function to ensure it's retained while it can call it's target.
class ViewController: UIViewController, UITextViewDelegate, UIScrollViewDelegate {
// Global Variables
var scrollView = UIScrollView()
var newNoteButton: UIButton! // <- Declare button here instead of in viewDidLoad
}