我有一个文本框,希望用户能够选择表情符号作为图标。目前,我可以将文本字段限制为仅包含1个字符,但我也希望用户能够轻松更改图标而无需按下“返回”键。任何在保持1个字符限制的情况下用新文本替换现有文本的解决方案。
extension ItemDetailViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if categoryTextField.isEditing {
let categoryText = categoryTextField.text ?? ""
guard let stringRange = Range(range, in: categoryText) else { return false }
let updatedText = categoryText.replacingCharacters(in: stringRange, with: string)
return updatedText.count <= 1
} else {
let oldText = self.textField.text!
let stringRange = Range(range, in: oldText)!
let newText = oldText.replacingCharacters(in: stringRange, with: string)
doneBarButton.isEnabled = !newText.isEmpty
return true
}
}
}