Is there any way to make UITextFieldDelegate more dynamic in swift? - swift

I nearly have a UITextFieldDelegate in a UIViewController,and I make
import UIKit
class testViewController: UIViewController,UITextFieldDelegate{
#IBOutlet weak var textName: UITextField!
override func viewDidLoad(){
super.viewDidLoad()
textName.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
}
it works very well.
but my question is, when i have two, or three UITextFields, and have different function,what should i do? Is there any way to make UITextFieldDelegate more dynamic in swift? just like java do? I remember that java may do like that:
textName.delegate = UITextFieldDelegate{
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
}
textAddress.delegate = UITextFieldDelegate{
func textFieldShouldReturn(textField: UITextField) -> Bool {
return true
}
}

The delegate methods take a parameter that identifies the text field for which the demarcate methods are being called. You can use this to provide different behaviours for different text fields.

Related

How start to UITextView from paragraph in Swift

How to start a new line in UITextView with a little space, called paragraph I believe?
What you need to do is make the controller confront to UITextFieldDelegate
for example:
class ViewController: UIViewController,UITextFieldDelegate
{
//link the textfield
#IBOutlet weak var textField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
// link the delegate to the textfield
textField.delegate = self
}
//this function detects the return button when it's pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
//since we always want to start a new line with space we override the default function
textField.text += "\n "
return false
}

How to set NSButton.isEnabled from subclassed NSTextField

I'm very new to Swift MacOS programming and have been learning by writing small test applications.
The aim of this application is to enable the pushbutton when the 2nd textfield has the focus, and disable it when it is not focused.
I have found that by subclassing the NSTextField I can override becomeFirstResponder() however don't know how to set the button to be disabled from the subclass.
ViewController:
class ViewController: NSViewController {
#IBOutlet public weak var pushButton: NSButton!
#IBOutlet weak var textField3: NSTextField!
#IBOutlet weak var textField2: GSTextField!
#IBOutlet weak var textField1: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
textField2.delegate = self
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func chgButton(onoff: Bool){
pushButton.isEnabled = onoff
}
}
// When the field completes editing make the pushbutton disabled.
extension ViewController: NSTextFieldDelegate {
override func controlTextDidEndEditing(_ obj: Notification) {
print("did end")
chgButton(onoff: false)
}
}
GSTextField.Swift
class GSTextField: NSTextField {
override func becomeFirstResponder() -> Bool {
print("GSTextField Firstresponder")
////*** I need to set the button to be enabled here
return super.becomeFirstResponder()
}
}
Your NSTextField subclass needs to be able to communicate with the pushButton. The easiest way to do this is to pass a reference to the pushButton to your text field and then update the push button from there.
Update your ViewController like this:
override func viewDidLoad() {
super.viewDidLoad()
textField2.delegate = self
textField2.pushButton = pushButton
// Do any additional setup after loading the view.
}
And your GSTextField like this:
class GSTextField: NSTextField {
weak var pushButton: NSButton?
override func becomeFirstResponder() -> Bool {
print("GSTextField Firstresponder")
pushButton?.isEnabled = true
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
pushButton?.isEnabled = false
return super.resignFirstResponder()
}
}
It should be noted that while this works fine in this toy example, this is a sub-optimal solution to this problem because it tightly couples the pushButton and the GSTextField. A better solution would be to use delegation to communicate the focus changes to the ViewController, and let the ViewController handle the updates.
Your GSTextField would look like this:
protocol FocusObservable: class {
func didGainFocus(sender: Any)
func didLoseFocus(sender: Any)
}
class GSTextField: NSTextField {
weak var focusDelegate: FocusObservable?
override func becomeFirstResponder() -> Bool {
print("GSTextField Firstresponder")
focusDelegate?.didGainFocus(sender: self)
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
focusDelegate?.didLoseFocus(sender: self)
return super.resignFirstResponder()
}
}
And then you would add protocol conformance to the ViewController:
extension ViewController: FocusObservable {
func didGainFocus(sender: Any) {
pushButton.isEnabled = true
}
func didLoseFocus(sender: Any) {
pushButton.isEnabled = false
}
}
and set the focusDelegate of the text field:
override func viewDidLoad() {
super.viewDidLoad()
textField2.delegate = self
textField2.focusDelegate = self
// Do any additional setup after loading the view.
}

Keyboard not being dismissed

I realize this is a trivial question with tons of answer on SO. I may just need a pair of fresh eyes as I've triple checked everything and cannot see where I am going wrong with this. I just want to dismiss the keyboard on hitting the return key. I'm setting the delegate properly and implementing the proper methods, so why won't the keyboard dismiss?
Does having a collectionView in the viewController complicate things? (text field is NOT inside collectionView)
class SearchController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {
#IBOutlet weak var searchBar: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
setupUI()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
searchBar.resignFirstResponder()
return true
}
Things I've tried:
cleaning the project
restarting xcode
changing the searchBar.resignFirstResponder() to textField.resignFirstResponder()
setting the delegate for the text field inside IB instead of in viewDidLoad
What the heck am i missing here!?
You need to implement the proper text field delegate method. There is no such delegate method as textFieldShouldReturn(textField:). The proper method is textFieldShouldReturn(_:).
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
searchBar.resignFirstResponder()
return false
}
The _ makes a huge difference. You may have copied an old Swift 2 implementation.
It's best to let Xcode perform code completion to ensure you get the correct signature of any method you are implementing or calling.
Use this code
view.endEditing(true)

textfield not empty show save button in Swift

My save button is hidden with the function saveBtnHidden() in the code below. However, the save button won't reappear when text is typed into the text field. I have tried multiple solutions similar to this. Every time that I type into the text field, the save button just won't show up.
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var nicknameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
saveBtnHidden()
}
func saveBtnHidden() {
if (nicknameField.text?.isEmpty ?? true) {
// is empty
saveBtn.isHidden = true
} else {
saveBtn.isHidden = false
}
}
#IBAction func saveBtnPressed(_ sender: Any) {
performSegue(withIdentifier: "nextPage", sender: nil)
}
}
You are getting this error because your function saveBtnHidden() is only called once in viewDidLoad(). It does not get called again when the text in your text field changes. To detect when text changes, you will need to add a target to your text field that calls a function when it changes (.editingChanged) like this:
nicknameField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
Then in the textFieldDidChange call your saveBtnHidden() function:
func textFieldDidChange(_ textField: UITextField) {
saveBtnHidden()
}
Code adapted from: How do I check when a UITextField changes?
Use delegate to be notify of any change. Delegates is a key part of iOS development and Apple's framework.
class TableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var saveBtn: UIButton!
#IBOutlet var nicknameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
saveBtnHidden()
nicknameField.delegate = self
}
func textFieldDidChange(_ textField: UITextField) {
saveBtnHidden()
}
// More of your source code below...

UITextFieldDelegate extension function does not triggers, why?

I have SequencedTextFields protocol, which contains sequence of text fields. When user taps Return button on keyboard, current text field should resign first responder and next text field in the sequence should become first responder. And it works good, when I'm using direct implementation of UITextFieldDelegate protocol for view controller:
extension MyViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
nextInSequence(after: textField)?.becomeFirstResponder()
return true
}
}
But, when I'm trying to use default implementation, it does not triggers ever:
extension UITextFieldDelegate where Self: SequencedTextFields {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
nextInSequence(after: textField)?.becomeFirstResponder()
return true
}
}
What could be the reason? Or I've missed something?
UPDATE:
My view controller defining:
final class MyViewController: UIViewController, UITextFieldDelegate, SequencedTextFields
Setting up the delegate for the text fields:
The reason why your implementation is not working is because you are trying to extend an interface (UITextFieldDelegate) instead of a class, that's why it works when you use UIViewController instead.
What you can do is to create a custom class SequencedTextField that extends UITextField. Add a custom delegate (that I called sequencedDelegate that represents the class that implements your SequencedTextFields protocol.
Extend SequencedTextField to implement UITextFieldDelegate with your default implementation.
On MyViewController, set up your SequencedTextField delegate with the viewController itself.
At the end it should look something like this:
protocol SequencedTextFields: class {
func nextInSequence(after: UITextField) -> UITextField?
}
class SequencedTextField: UITextField {
weak var sequencedDelegate: SequencedTextFields?
}
extension SequencedTextField: UITextFieldDelegate {
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
sequencedDelegate?.nextInSequence(after: textField)?.becomeFirstResponder()
return true
}
}
class MyViewController : UIViewController, SequencedTextFields {
var textField = SequencedTextField()
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = textField
textField.sequencedDelegate = self
}
func nextInSequence(after: UITextField) -> UITextField? {
// your view controllers nextInSequence implementation here
}
}
What is wrong with your code?
The first extension is the extension of your view controller MyViewController, that's why it is working. But the second one is the extension of UITextFieldDelegate. Those are completely two different things.
Not clear what you want to achieve.
This is how you can use your custom protocol
If you want to make one CustomProtocol for your special UITextField you can do like this.
CustomTextFieldProtocol
Declear the protocol
protocol SequencedTextFields: UITextFieldDelegate {
func checkSomeThing(_ textField: UITextField) -> Bool
}
Set the delegate
self.textField.delegate = self
ViewController Extension to implement your Delegate methods
extension ViewController: SequencedTextFields {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
nextInSequence(after: textField)?.becomeFirstResponder()
return true
}
func checkSomeThing(_ textField: UITextField) -> Bool {
print("Check here")
return true
}
}