Using #objc delegate methods with multiple arguments - ios

I want to be able to pass multiple arguments to a #selector() method other than only the sender itself.
Say, I have a UITextField which has a UITapGestureRecognizer, and I want some other class to be the delegate of this UITapGestureRecognizer. I write a delegate protocol for it called SomeDelegateProcotol. However, I also want to pass the instance of the UITextField to the delegate upon tap. I figured things might look something like this:
// The delegate
class Delegate: SomeDelegateProcotol {
private let textField = TextField()
func handleTapFromView(_ sender: UITapGestureRecognizer, textField: UITextField) {
print("Hey! I should handle the tap from the user.")
}
init() {
textField.delegate = self
}
}
// The protocol
#objc protocol SomeDelegateProtocol {
#objc func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
weak var delegate: SomeDelegateProtocol?
override init(frame: CGSize) {
super.init(frame: frame)
...
let gestureRecognizer = UITapGestureRecognizer(target: delegate!,
action: #selector(delegate!.handleTapFromView(_:, textField:
self)))
}
}
However, this is not the right syntax, as handleTapFromView(_:, textField: self) is invalid. This raises the following questions to which I haven't found a solution yet:
What exactly means this syntax? (_:). I assume it's passing itself, but the UITapGestureRecognizer is not created yet?
How do I successfully pass the TextField instance to the delegate alongside the sender?

I would suggest keeping things as simple as this,
protocol SomeDelegateProtocol: class {
func handletapFromView(_ sender: UITapGestureRecognizer, textField: UITextField)
}
class TextField: UITextField {
weak var someDelegate: SomeDelegateProtocol?
override init(frame: CGRect) {
super.init(frame: frame)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(tap(_:)))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc private func tap(_ sender: UITapGestureRecognizer) {
self.someDelegate?.handletapFromView(sender, textField: self)
}
}

Related

How to add target to UITextField in a class other than ViewController

I am trying to write a class that has a method which observe text changes on UITextField objects.
When in ViewController, code below works as intended:
class ViewController: UIViewController {
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.addTarget(view, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
#objc func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
So i wrote a class and put methods in it as below:
internal class ListenerModule: NSObject, UITextFieldDelegate {
internal func textWatcher(textField: UITextField!, view: UIViewController!) {
textField.delegate = self
textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
}
#objc internal func textFieldDidChange(_ textField: UITextField) {
print(textField.text!)
}
}
//And in ViewController,
...
ListenerModule().textWatcher(textField: password, view: self)
...
But it does not work.
How can i add target to a TextField in a class or a library?
I think it could be because you are not persisting with your ListenerModule object.
I believe you are doing this ListenerModule().textWatcher(textField: password, view: self) in some function so the scope of the object created is limited to that function.
You could do the following:
// Globally in your UIViewController subclass
var listenerModule: ListenerModule?
// Some set up function after text field is initialized
private func setup()
{
listenerModule = ListenerModule()
// Then call the text watcher, not sure why you pass the view,
// doesn't seem like you use it
listenerModule?.textWatcher(textField: password, view: self)
}
Give this a try and see if this solves your issue

Calling delegate methods in custom UITextField class

So this might be basic Swift knowledge but I'm struggling to find this info anywhere online. I'm trying to create a custom text field glass with global styles that utilizes UITextFieldDelegate methods. In particular I'm trying to use the function textFieldDidBeginEditing(). In my example below I'm just trying to print "hello" when a text field is being edited, however nothing is being printed to the console when I begin typing in my custom text field.
If I'm doing anything incorrectly please let me know, as I don't work with Swift too much. Thank you!
class LoFMTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
styleTextField()
}
required init?(coder LoFMDecoder: NSCoder) {
super.init(coder: LoFMDecoder)
styleTextField()
}
func styleTextField() {
layer.cornerRadius = 5.0
layer.borderWidth = 1.0
layer.borderColor = UIColor.white.cgColor
backgroundColor = UIColor.white
}
}
extension UITextFieldDelegate {
func textFieldDidBeginEditing(textField: UITextField!) {
print("hello")
}
}
Add this line inside styleTextField
self.delegate = self
Then
extension LoFMTextField : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
print("hello")
}
}
Note: it's (_ textField: UITextField) not (textField: UITextField!)

Can I chain delegates together?

Swift 4.0 iOS 11.x
I have created a simple text field class, that uses the UITextFieldDelegate. I wanted to add to it an additional protocol that I could use to pass on the fact that the text entry to said field completed. A Delegate chain, since once I have picked up the fact that text entry has exited in the custom class I cannot pass it down to the VC in which the UITextField class is within it seems.
import UIKit
protocol ExitedFieldDelegate {
func exited(info: String)
}
class IDText: UITextField, UITextFieldDelegate {
internal var zeus: ExitedFieldDelegate? = nil
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
delegate = self
}
required override init(frame: CGRect) {
super.init(frame: frame)
delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.textColor = UIColor.black
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
if (delegate != nil) {
let info = self.text
zeus?.exited(info: info!)
}
}
}
I added this code to the viewController I wanted to use my custom class within.
class ConfigViewController: UIViewController, ExitedFieldDelegate
And of course the method required by the protocol
func exited(info: String) {
print("The brain has left the room")
}
And I made it a delegate of said protocol so I got this in effect
var blah = IDText()
blah.delegate = self
But well it doesn't work. Am I attempting the impossible here, should I simply use default notifications instead? or indeed something else?
By setting:
blah.delegate = self
You are overwriting setting the delegate to self in the initializers.
What you want is to rewrite:
internal var zeus: ExitedFieldDelegate? = nil
to:
weak var zeus: ExitedFieldDelegate?
To be able to use weak (you want that to prevent retain cycle), update protocol definition to:
protocol ExitedFieldDelegate: class {
func exited(info: String)
}
And then change this:
var blah = IDText()
blah.delegate = self
to:
var blah = IDText()
// you want to set zeus instead of the delegate field
blah.zeus = self

Swift: recognize when UITextField is tapped

I am new to swift and have been stuck on this for hours. I am trying to recognize when a UITextField is tapped by the user, and call some function. For some reason I keep getting "unrecognized selector sent to instance".
Here is my attempt at a solution
and
Here is the error thrown
Any help is greatly appreciated!
Your selector is not pointing to the method! Try this instead:
textField.addTarget(self, action: #selector(ViewController.tapped(_:)), for: UIControlEvents.touchDown)
Also, instead of this approach you could also set ViewController as the delegate for textField and implement this:
extension ViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
print("tapped")
textField.backgroundColor = UIColor.blue
}
}
Use: action: #selector(ViewController.tapped())
Also, below that, add this: self.textField.delegate = self
you can simply perform you action in UITexFieldDelegate,
by making
myTextField.delegate = self
and use the method
optional public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
//perform you action here
return true
}
instead of finding a way to get tap event you can use textFieldDidBeginEditing function:
class ViewController: UIViewController, UITextFieldDelegate
{
#IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
func textFieldDidBeginEditing(textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(textField: UITextField) {
print("TextField did end editing method called")
}
}

iOS/Swift: how to detect touch action on a UITextField

I would like to detect the touch action on a UITextField.
It seems the "Touch Up Inside" action is not fired by touching inside the textfield.
It seems "Touch Up Inside" is not enabled for UITextField, but "Touch Down" works.
So the solution is as follows:
Swift 4.x
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
#objc func myTargetFunction(textField: UITextField) {
print("myTargetFunction")
}
Swift 3.x
myTextField.addTarget(self, action: #selector(myTargetFunction), for: UIControlEvents.touchDown)
#objc func myTargetFunction(textField: UITextField) {
print("myTargetFunction")
}
Swift 4 and higher:
class ViewController: UIViewController, UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
print("You edit myTextField")
}
}
}
This is a delegate function.
here's Swfit:
and you don't need to use the "touchUpInside" just use the delegate methods like so:
Make your View controller a delegate:
class ViewController: UIViewController, UITextFieldDelegate{
func textFieldDidBeginEditing(textField: UITextField) -> Bool {
if textField == myTextField {
return true // myTextField was touched
}
}
Here's the other delegate methods:
protocol UITextFieldDelegate : NSObjectProtocol {
optional func textFieldShouldBeginEditing(textField: UITextField) -> Bool // return NO to disallow editing.
optional func textFieldDidBeginEditing(textField: UITextField) // became first responder
optional func textFieldShouldEndEditing(textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
optional func textFieldDidEndEditing(textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text
optional func textFieldShouldClear(textField: UITextField) -> Bool // called when clear button pressed. return NO to ignore (no notifications)
optional func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
}
from swift docs:
struct UIControlEvents : RawOptionSetType {
init(_ rawValue: UInt)
init(rawValue: UInt)
static var TouchDown: UIControlEvents { get } // on all touch downs
static var TouchDownRepeat: UIControlEvents { get } // on multiple touchdowns (tap count > 1)
static var TouchDragInside: UIControlEvents { get }
static var TouchDragOutside: UIControlEvents { get }
static var TouchDragEnter: UIControlEvents { get }
static var TouchDragExit: UIControlEvents { get }
static var TouchUpInside: UIControlEvents { get }
static var TouchUpOutside: UIControlEvents { get }
static var TouchCancel: UIControlEvents { get }
static var ValueChanged: UIControlEvents { get } // sliders, etc.
static var EditingDidBegin: UIControlEvents { get } // UITextField
static var EditingChanged: UIControlEvents { get }
static var EditingDidEnd: UIControlEvents { get }
static var EditingDidEndOnExit: UIControlEvents { get } // 'return key' ending editing
static var AllTouchEvents: UIControlEvents { get } // for touch events
static var AllEditingEvents: UIControlEvents { get } // for UITextField
static var ApplicationReserved: UIControlEvents { get } // range available for application use
static var SystemReserved: UIControlEvents { get } // range reserved for internal framework use
static var AllEvents: UIControlEvents { get }
}
UITextField doesn't respond to "touchUpInside" see to the right side, you'll find it's acceptable control events
Update For Swift 3
Here is the code for Swift 3:
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
This is the function:
func myTargetFunction() {
print("It works!")
}
I referred to the UIControlEvents documentation from Apple and came up with the following:
First add UITextFieldDelegate to your class then,
textBox.delegate = self
textBox.addTarget(self, action: #selector(TextBoxOn(_:)),for: .editingDidBegin)
textBox.addTarget(self, action: #selector(TextBoxOff(_:)),for: .editingDidEnd)
with the following functions:
func TextBoxOff(_ textField: UITextField) {
code
}
}
func TextBox(_ textField: UITextField) {
code
}
}
For Swift 3.1:
1) Create a gesture recognizer:
let textViewRecognizer = UITapGestureRecognizer()
2) Add a handler to the recognizer:
textViewRecognizer.addTarget(self, action: #selector(tappedTextView(_:)))
3) Add the recognizer to your text view:
textView.addGestureRecognizer(textViewRecognizer)
4) Add the handler to your class:
func tappedTextView(_ sender: UITapGestureRecognizer) {
print("detected tap!")
}
To make this a little clearer these things need to be in place. I used this to make it so if a user entered something in an app of my own's credit textField anything in the debit textField is deleted.
UITextFieldDelegate needs to be declared in the View controller i.e class SecondViewController:
The detector functions func myDebitDetector func myCreditDetector need to be in the ViewController class.
put debit.addTarget and credit.addtarget inside view will appear.
#IBOutlet weak var debit: UITextField! and #IBOutlet weak var credit: UITextField! are textfields on the storyboard and connected to the viewController.
class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
#IBOutlet weak var credit: UITextField!
#IBOutlet weak var debit: UITextField!
func myDebitDetector(textfield: UITextField ){
print("using debit")
credit.text = ""
}
func myCreditDetector(textfield: UITextField) {
print("using cedit")
debit.text = ""
}
override func viewWillAppear(animated: Bool) {
debit.addTarget(self, action: "myDebitDetector:", forControlEvents: UIControlEvents.TouchDown)
credit.addTarget(self, action: "myCreditDetector:", forControlEvents: UIControlEvents.TouchDown)
....
}
}
Set the UITextField delegate to your view controller
Obj-C
textField.delegate = self;
Swift
textField.delegate = self
Implement the delegate method
Obj-c
-(void)textField:(UITextField*)textField didBeginEditing {
// User touched textField
}
Swift
func textFieldDidBeginEditing(textField: UITextField!) { //delegate method
}
Swift 3.0 Version:
textFieldClientName.addTarget(self, action: Selector(("myTargetFunction:")), for: UIControlEvents.touchDown)
Swift 4.2.
Try .editingDidEnd instead of .touchDown and delegate.
myTextField.addTarget(self, action: #selector(myTargetFunction), for: .editingDidEnd)
#objc func myTargetFunction(textField: UITextField) {
print("textfield pressed")
}
On xamarin.iOS i easy to use:
YourTextField.WeakDelegate = this;
[...]
[Export("textFieldDidBeginEditing:")]
public void TextViewChanged(UITextField textField)
{
if (YourTextField.Equals(textField))
IsYourTextFileFocused = true;
}
** Swift 4.0 + **
Use custom action like this
YourTextField.addTarget(self, action: #selector(myTargetFunction(_:)), for: .allEditingEvents)
#IBAction private func myTargetFunction(_ sender: Any) {
if let textField = sender as? UITextField {
// get textField here
}
}

Resources