你能解释下面的代码,尤其是func语句

时间:2016-07-23 05:28:43

标签: ios swift xcode

详细解释这一点(代码的每一行),我理解它的作用,但我很难将其解释为代码中的注释:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let text = (lvl1_textfield.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

if text.isEmpty{
        guess_enter.hidden = true
    } else {
        guess_enter.hidden = false
    } 
    return true
}

1 个答案:

答案 0 :(得分:0)

如果您对UITextFieldDelegate see this example有任何疑问。

在类型字符到达文本字段之前调用此函数。该函数主要用于验证。

只是为了理解我编写的小代码会发生什么。

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    print("TextField \(textField.text!), Range \(range), string \(string)")
    return true;
 }

当我键入n控制台打印 - >>> TextField,Range(0,0),string n

下一步如果我按下控制台打印 - >>> TextField n,Range(1,0),string a

下一步如果我按v控制台打印 - >>> TextField na,Range(2,0),string v

在您声明文字的第二行中,您获取textView中存在的字符串和最近输入的字符,然后使用范围附加,然后代码检查空标准。