UITextField with PickerView: Don't allow editing - ios

I have a UITextField associated with a PickerView (the PickerView is the inputView of the textField)
Il works fine, but I would like to disallow editing in my TextField (not be able to select, copy text, to see the insertion point, ...).
I red here to implement textField shouldChangeCharactersInRange, for the delegate of the uITextField, but it doesn't work...
The method is never called, but the delegate is correctly done, because if I implement textFieldShouldBeginEditing, it is called.
Is there any (simple) way to do what I want?

give your UITextField id and then implement textFieldShouldBeginEditing delegate. Inside those delegate, check the textField id, if it matches your desired textField, run function to called your picker view and return false in textFieldShouldBeginEditing delegate.

The following disallows pasting and cutting text unless the result is exactly the result from the picker. For example purposes I'm assuming this is a UIDatePicker.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
return string == formatter.stringFromDate(datePickerView.date)
}
where formatter is something like
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateFormat = "dd/MM/yyyy"
Additionally, if you programmatically set the textfield to a string date, you may want to synchronize the inputView picker of the textField with
func textFieldShouldBeginEditing(textField: UITextField) -> Bool
{
if let text = textField.text {
if let date = formatter.dateFromString(text) {
datePickerView.setDate(date, animated: true)
}
}
return true
}

Related

Is there a way to hide a UILabel when the user starts typing, and then make it re-appear if the user removes all input?

I'm trying to implement a search field where you type in some characters to show "possible searches". In the beginning there is a small text underneath the textbox that says "make sure to capitalize letters". This is just a UILabel. I want to make this label "disappear" when the user STARTS to type. But if the user backspaces enough to remove all text - I want the label to re-appear again.
The textbox is just made from UITextField.
This is all stored in a view.
Does anyone have an idea of how to implement something like this?
You Can do it using add a target to your textFiled with a selector like this
add this target to ur viewDidLoad method
yourTextFiled.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
create selector method like this below your viewDidLoad Method and set if textfield.text.isEmpty than label is hidden like this
#objc func textFieldDidChange(_ textField: UITextField) {
if textField.text!.isEmpty {
label.isHidden = false
} else {
label.isHidden = true
}
}
Hope you get your desire thing !
You can do this by the textfield delegate method shouldChangeInCharacter and check when textfield is empty set the label isHidden property to false otherwise too true.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text {
if text.isEmpty {
label.isHidden = false
}
else {
label.isHidden = true
}
}
return true
}
Hope this will help you. Happy coding!

TextField and Warning

I have a UITextField object and take input from the textfield. If length of the input is shorter than 2, I want to give warning sign in the textfield bar.
Is this impossible ?
If it is so, how can I handle that ?
EDIT:
I just handled it. I put a label in the textfield and run auto layout. Then, I chose delegate of textfield and make InputViewController conform to UITextFieldDelegate protocol. Finally, I use func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
Implement UITextFieldDelegate in your view controller and use textFieldDidEndEditing to check text length.
func textFieldDidEndEditing(_ textField: UITextField) {
if let textFieldText = textField.text {
print("textFieldText length - \(textFieldText.count)")
if (textFieldText.count < 2) {
showWarning(message: "Your message here")
}
}
}
func showWarning(message: String?){
// show warning message using UIAlertController here.
}
You can use a custom class inherited from UIView and pack UITextField(No border style) and Iconic Font UILabel inside it.

UITextFields should get active in reverse order

I have six UITextFields one after another which is used for typing passcode.
after one character, next UITextFields becomes active. But how to do for backspace? On keyboard backspace, text field should get active in reverse order
For your requirement, I made a demo and it is working like a charm.
So in order to fulfill your requirement you have to follow below instructions:
Give tag to every UITextField in order like 101,102,103,104,105 and 106
Then make every textField's delegate to self (UIViewController)
Then implement UITextField's below delegate method
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("string = \(string) text = \(textField.text)")
if(textField.text?.characters.count == 1){
if string.characters.count == 0{
if textField.tag != 101{
textField.resignFirstResponder()
let preField : UITextField = self.view.viewWithTag(textField.tag-1) as! UITextField
preField.becomeFirstResponder()
}
textField.text = string
return false
}
if textField.tag != 106{
textField.resignFirstResponder()
let nextField : UITextField = self.view.viewWithTag(textField.tag+1) as! UITextField
nextField.text = string
nextField.becomeFirstResponder()
}
return false
}
return true
}

what function can help me to know user input first character in textfield and how to make a blank line when I press keyboard return?

I have two problems.I am a beginner of swift
First,I want to hide the send button until user input frist character.I use textfield delegate functions that they don't implement this idea.
And then, I want to creat a blank line when user input in textfield.I know to use "textFieldShouldReturn" function ,but I use "\n" that it doesn't work for me.How to do this?
this is my code:
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text?.isEmpty == false {
aButton.isHidden = true
sendButton.isHidden = false
}
}
update code:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.textField.text = "\n"
return true
}
I also want the textfield change it height.let user can input their message. Does it can be implement?
Or I need to change textfield to textview.
You can use textfields delegate method to check when user start writing something in your textfield.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if textField == txtUserName //compare with your textfield object which you have taken by outlet
{
if string.characters.count >= 1 {
//make your button enable
}else
{
// disable your button
}
}
return true
}

Change 'Return' button function to 'Done' in swift in UITextView

I would like to get rid of the "return" function of the keyboard while the user is typing, so there are no new lines, so instead I would like the 'return' key to function as 'Done' so it would hide the keyboard.
I am using a UITextView, that is editable, so the user is able to type their post, and post it to the main timeline, but since I have fixed cells, I don't want the user to be able to press 'return' and their post would be out of range of the timeline.
I found this that works with UITextField, but not with UITextView:
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder() //if desired
return true
}
So I just wanted to know if there is a way to do that in a UITextView, or at least to be able to hide the keyboard if pressed return, instead of creating a new line.
You can set the return key type of the text field:
textField.returnKeyType = UIReturnKeyType.done
Update
You can definitely use the same approach to set the return key to "Done", as mentioned above. However, UITextView doesn't provide a callback when user hits the return key. As a workaround, you can try to handle the textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) delegate call, and dismiss the keyboard when you detect the input of a new line character:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
textView.resignFirstResponder()
}
return true
}
I have tried many codes and finally this worked for me in Swift 3.0 Latest [April 2019] this achieved using UITextFields
The "ViewController" class should be inherited the "UITextFieldDelegate" for making this code working.
class ViewController: UIViewController,UITextFieldDelegate
Add the Text field with the Proper Tag number and this tag number is used to take the control to appropriate text field based on incremental tag number assigned to it.
override func viewDidLoad() {
userNameTextField.delegate = self
userNameTextField.tag = 0
userNameTextField.returnKeyType = .next
passwordTextField.delegate = self
passwordTextField.tag = 1
passwordTextField.returnKeyType = .go
}
In the above code, the "returnKeyType = UIReturnKeyType.next" where will make the Key pad return key to display as "Next" you also have other options as "Join/Go" etc, based on your application change the values.
This "textFieldShouldReturn" is a method of UITextFieldDelegate controlled and here we have next field selection based on the Tag value incrementation.
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
return true;
}
return false
}
If you're working with a storyboard or xib, you can change the UITextView's Return button to 'Done' (or various other options) within Interface Builder, without the need for any setup code. Just look for this option in the Attributes inspector:
From there, you just pair it up with the UITextViewDelegate code that others have already provided here.
Swift v5:
extension ExampleViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
textView.resignFirstResponder()
}
return true
}
}
And then, in your viewDidLoad() method:
exampleTextView.delegate = self
Working in Swift 4
Add this in viewDidLoad().
textField.returnKeyType = UIReturnKeyType.Done
Add this anywhere you like.
extension UITextView: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
if text.last == "\n" { //Check if last char is newline
text.removeLast() //Remove newline
textView.resignFirstResponder() //Dismiss keyboard
}
}
}

Resources