Minimum characters for a text field? (Swift) - ios

I´m currently working on a login and registration(Xcode 7, Swift2). If a user registers and types his desired username in the text field,i would like him to type at least 5 characters. So if he leaves the text field and haven´t typed in at least 5 characters, a message get´s displayed that tells him to type in at least 5 characters.
I only found how to determine the maximum amount of characters, but was not able to adjust it to my needs.
This is my current code:
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
// Mark: Properties
#IBOutlet weak var Username: UITextField!
#IBOutlet weak var Password: UITextField!
#IBOutlet weak var Status: UILabel!
#IBOutlet weak var DesiredUsername: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Mark: Actions
#IBAction func CreateAccount(sender: UIButton) {
}
#IBAction func LoginButtonTapped(sender: UIButton) {
if (Username.text == "janoschvongehr" && Password.text == "test123") {
performSegueWithIdentifier("SeguetoPeople", sender: nil)
}
if (Username.text == "" || Password.text == "") {
Status.text = "Nicht alle Felder ausgefüllt"
}
self.Username.resignFirstResponder()
self.Password.resignFirstResponder()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
I just started with programming, so it would be great if you could keep the answers as simple as possible.
Thank you, guys!

func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField.text!.characters.count < 5 {
warningLabel.hidden = false
}
self.view.endEditing(true)
return true
}
should do the trick.

Seems like you are 90% of the way there, especially in the fact you already set a delegate for your text field.
Try doing:
func textFieldShouldReturn(textField: UITextField) -> Bool {
if ( textField.text.count < 5 )
{
// create a warning label IBOutlet and set it to hidden
//
// reveal it only upon leaving the text field when the
// length is less than 5
warningLabel.hidden = false;
}
self.view.endEditing(true)
return true
}

Related

I want to be able to edit text fields in the order specified by the tags. A lot of research to no avail. I am somewhat of a novice

Can not get the the fields to edit in the order of the tags. In this scenario I have four fields on a screen in a two columns and two rows. I want to be able to be able to edit down column 1 and the column2. By default it goes across row 1 then to row2.
This is part of much larger project I am working on. This is a critical feature as there are quite a few more fields (more than 20). I've tried using TextDidEndEditing too. That didn't help.
import UIKit
import os.log
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var Par1: UITextField!
#IBOutlet var Par2: UITextField!
#IBOutlet var Par3: UITextField!
#IBOutlet var Par4: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Par1.delegate = self
Par1.tag = 0
Par2.delegate = self
Par2.tag = 1
Par3.delegate = self
Par3.tag = 2
Par4.delegate = self
Par4.tag = 3
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
var nextTag:Int
textField.resignFirstResponder()
if (textField.tag == 3) {
nextTag = 0
} else {
nextTag = textField.tag + 1
}
if let nextResponder = textField.superview?.viewWithTag(nextTag) as? UITextField {
nextResponder.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return true
}
#IBAction func Par1Entered(_ sender: UITextField) {
Par1.text = sender.text
}
#IBAction func Par2Entered(_ sender: UITextField) {
Par2.text = sender.text
}
#IBAction func Par3Entered(_ sender: UITextField) {
Par3.text = sender.text
}
#IBAction func Par4Entered(_ sender: UITextField) {
Par4.text = sender.text
}
}
Make the field tags sequential and the in textFieldShouldReturn do the following:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
if let nextResponder = textField.superview?.viewWithTag(nextTag) {
nextResponder.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
If you want to go to the next field without hitting the Next keyboard button there are a few other ways to achieve this.

Not able to set textfield as becomeFirstResponder() with textfield outlet collection in tvos

I took text field outlet collection and bind six text field over there.
I want to becomeFirstResponder of next text field which is in text field outlet collection.
I gave textfields tag 0 to 5 from storyboard.
see,
Main ViewController:
class ViewController: UIViewController {
#IBOutlet var txtSignUp: [UITextField]!
var arrayPlaceHolder:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
arrayPlaceHolder = NSArray(array: ["1","2","3","4","5","6"])
self.setTextFieldValue()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setTextFieldValue(){
for txtField in txtSignUp{
let tagTxt = txtField.tag
txtField.attributedPlaceholder = NSAttributedString(string:arrayPlaceHolder[tagTxt] as! String, attributes:[NSForegroundColorAttributeName:UIColor.black])
if(tagTxt != ((arrayPlaceHolder.count) - 1)){
txtField.returnKeyType = .next
}
txtField.delegate = self
}
}
}
extension ViewController:UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
for txt in txtSignUp{
let nextTxt = (textField.tag + 1)
if txt.tag == nextTxt {
txt.becomeFirstResponder()
break
}
}
return true
}
}
Error:
whose view is not in the window hierarchy!
Explanation:
In this code, I am not able to become next text field as becomeFirstResponder.
Can anyone help me to resolve this issue.
On TVos you have to use the textFieldDidEndEditing function because textFieldShouldReturn won't work to set the next responder:
class MyViewController: UIViewController{
#IBOutlet weak var firstTextField: UITextField!
#IBOutlet weak var secondTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
firstTextField.delegate = self
secondTextField.delegate = self
firstTextField.tag = 0
secondTextField.tag = 1
}
}
extension MyViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if (textField.tag == 0){
secondTextField.becomeFirstResponder()
}
}
}

Swift get textbox value surounded by optional()

My ViewController
/ MARK: Properties
#IBOutlet weak var textInput: UITextField!
#IBOutlet weak var labelTop: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
textInput.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
if (textInput != nil){
labelTop.text = "Searching for \(textField.text)"
textInput.enabled = false
}
}
When I press return on the textfield the code
labelTop.text = "Searching for \(textField.text)"
is called. However the text of labelTop looks like:
Searching for Optional("the text")
I looked at optionals (most times they use ? instead of ! right?) but do not understand how I should get the value without the surrounding 'Optional("")'
You need to unwrap the optional value.
if let text = textInput?.text {
labelTop.text = text
textInput.enabled = false
}

keyboard controlling function error with Xcode 7

I was trying to create a function in order to put keyboard away by clicking outside of the keyboard or return key within the keyboard, but unfortunately it only worked when I clicked outside of the keyboard, it doesn't work to press the return key in the keyboard.
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
#IBOutlet var numberEnter: UITextField!
#IBAction func findButton(sender: AnyObject) {
resultLabel.text = numberEnter.text
}
#IBOutlet var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField:UITextField) -> Bool{
textField.resignFirstResponder()
return true
}
}
If you haven't set the delegate for your text field you will need to do that. You can set the delegate in Interface Builder or in code. See this StackOverflow answer for an example: Text Field Should Return, is this correct for ios7?

Printing input from TextField to a Label in Xcode with Swift

I'm working on a simple guessing game app, just to get more comfortable with Swift and Xcode. I have been able to input within userInput and get it to print a message to the console, however when I try to get it to print my input to usersGuess(which is a label), I can not figure it out.
Here's my code within a single view application via Xcode:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var correctAnswerLabel: UILabel!
#IBOutlet weak var usersGuess: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonPressed() {
correctAnswerLabel.text = "Changes when the button is pressed."
}
#IBAction func userInput(sender: UITextField) {
println("This is working")
}
}
I'm sure this is simple, but I am scratching my head lol.
#IBAction func userInput(sender: UITextField) {
println("This is working")
usersGuess.text = sender.text
}
Although I am still new to iOS dev and Swift, I think you could also take a look at the use of delegate in this tutorial Apple provides. I guess it might be the code didn't resign your text field's first-responder status. Hence, the usersGuess could not update. (Anyone who knows how this work please leave a comment.)
To do this, basically
Create an outlet for the UITextField that receives user's input, say, usersInput.
Set ViewController as a delegate of usersInput, which will
Resign the first-responder status of usersInput when the Return button on the keyboard is pressed.
Update the text of usersGuess.
Code here:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var correctAnswerLabel: UILabel!
#IBOutlet weak var usersGuess: UILabel!
#IBOutlet weak var usersInput: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Set ViewController as a delegate
usersInput.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Here are the callback functions for usersInput
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
usersGuess.text = textField.text
}
#IBAction func buttonPressed() {
correctAnswerLabel.text = "Changes when the button is pressed."
}
#IBAction func userInput(sender: UITextField) {
println("This is working")
}
}

Resources