Swift 在文本字段中键入时保存最后一个字母
我的应用程序中有以下功能:Swift 在文本字段中键入时保存最后一个字母,swift,uitextfield,Swift,Uitextfield,我的应用程序中有以下功能: func typingName(textField:UITextField){ if let typedText = textField.text { tempName = typedText print(tempName) } } 在viewDidLoad()中,我写了以下内容: textField.addTarget(self, action: #selector(typingName), for: .editin
func typingName(textField:UITextField){
if let typedText = textField.text {
tempName = typedText
print(tempName)
}
}
在viewDidLoad()
中,我写了以下内容:
textField.addTarget(self, action: #selector(typingName), for: .editingChanged)
所有工作正常,但我只想保存用户键入的字母
使用此函数,如果我写“hello”,它将打印:
“h”
“他”
“hel”
“见鬼”
“你好”
相反,我想要这个:
“h”
“e”
“l”
“l”
“o”。对于任何Swift字符串,您都可以从如下字符串中获取最新字母:
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
}
由于您正在收听事件,您在键入name
功能中需要做的就是:
func typingName(textField:UITextField){
if let typedText = textField.text {
tempName = typedText
print(tempName)
if let lastCharacter = tempName.characters.last {
print(lastCharacter)
}
}
}
看看这个
let tempName = "Hello"
print(tempName.characters.last)
如果要获取用户用键盘输入的最后一个字符 您可以使用
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
}
}
“字符”不可用:请直接使用字符串