删除最后一个字符 UITextField
我有一个 UITextField,我希望每次点击一个字符时,第一个字符都会被删除。这样我每次在文本字段中只有一个字符。此外,我希望它显示控制台日志中的每个点击。
我该怎么做?
I have an UITextField and I would like that for every tap on a character, the first character is deleted. So that I just have one character in my textField every time. Moreover I would like it to display every tap in the console log.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在文本字段委托中实现
shouldChangeCharactersInRange
方法:您可能需要检查范围和字符串值以涵盖所有可能的情况(例如复制/粘贴操作)。此代码只是将文本字段的值设置为最后键入的字符。
You need to implement
shouldChangeCharactersInRange
method in your text field delegate:You may need to check for range and string values to cover all possible cases (like copy/paste actions). This code just sets the text field's value to the last typed character.
UITextField 继承自 UIControl,因此您可以使用 UIControl 类中的目标操作机制:
在操作方法中,您可以仅使用最后一个字符替换 UITextField 的文本,并将该字符记录在控制台中。请注意,由于更改 UITextField 的文本将再次导致“updateTextField”消息第二次发送到目标,因此您将需要某种机制来确定是否更新:
或者类似的东西......
UITextField inherits from UIControl, so you can use the target-action mechanism that is part of the UIControl class:
In the action method, you can replace the UITextField's text with only the last character and log that character in the console. Note that since changing the UITextField's text will again result in the "updateTextField" message being sent a second time to the target, you will need some kind of mechanism for determining whether to update or not:
Or something like that anyway...