在textField中键入时保存最后一个字母

时间:2017-07-06 07:34:11

标签: swift uitextfield

我的应用程序中有这个功能:

func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)
    }
}

viewDidLoad()我写过:

textField.addTarget(self, action: #selector(typingName), for: .editingChanged)

一切正常,但我只想保存用户输入的字母。

使用此功能,如果我写"你好"它打印: " H" "他" " HEL" "地狱" "你好&#34 ;.

相反,我想拥有这个: " H" " E" " L" " L" " O"

3 个答案:

答案 0 :(得分:2)

如果您想获得用户使用键盘输入的最后一个字符。

您可以使用UITextField的委托方法检测它,如下面的代码所示:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var tfName: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        //Need to confirm delegate for textField here.
        tfName.delegate = self
    }

    //UITextField Delegate Method
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //This will print every single character entered by user.
        print(string)
        return true
    }
}

答案 1 :(得分:0)

对于任何Swift String ,您可以从这样的字符串中获取最新的字母:

let myString = "Hello, World"
let lastCharacter = myString.characters.last // d

请注意,lastCharacter的数据类型是字符?(可选character),您可能希望将其作为可选绑定:

let myString = "Hello, World"
if let lastCharacter = myString.characters.last {
    print(lastCharacter) // d
}

由于您正在收听editingChanged事件,因此您在typingName功能中所要做的就是:

func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)

        if let lastCharacter = tempName.characters.last {
            print(lastCharacter)
        }
    }
}

答案 2 :(得分:0)

检查出来

let tempName = "Hello"
print(tempName.characters.last)
相关问题