我目前正在进行登录和注册(Xcode 7,Swift2)。如果用户在文本字段中注册并输入他想要的用户名,我希望他输入至少5个字符。因此,如果他离开文本字段并且没有输入至少5个字符,则会显示一条消息,告诉他输入至少5个字符。 我只找到了如何确定最大字符数,但无法根据我的需要进行调整。 这是我目前的代码:
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
}
}
我刚开始编程,所以如果你能尽可能简单地保持答案就会很棒。 谢谢你们,伙计们!
答案 0 :(得分:1)
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField.text!.characters.count < 5 {
warningLabel.hidden = false
}
self.view.endEditing(true)
return true
}
应该这样做。
答案 1 :(得分:0)
看起来你已经90%了,尤其是你已经为你的文本字段设置了委托。
尝试做:
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
}