2017-07-06 47 views
2

我在我的应用程序这个功能:保存的最后一个字母

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

viewDidLoad()我写了这个:

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

所有作品不错,但我想保存只有用户输入的字母。

有了这个功能,如果我写 “你好” 它打印: “H” “他” “HEL” “地狱” “你好”。

相反,我想有这样的: “H” “E” “L” “L” “O”。

回答

0

对于任何斯威夫特字符串,你可以得到一个字符串像这样最新的信:

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) 
     } 
    } 
} 
0

检查这出

let tempName = "Hello" 
print(tempName.characters.last) 
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 
    } 
} 
相关问题