如何在单击按钮时从文本字段中删除光标?
我正在尝试执行一项简单的任务:
我有一个可编辑的文本字段,窗口上方有两个按钮(标题:使可编辑/使不可编辑)。想法是:当用户单击“使可编辑”按钮时,文本字段应变为可编辑,当他/她单击“使不可编辑”时,文本字段应变为不可编辑。
在“使不可编辑”的操作中,我正在执行此操作:
[myTextField setSelectable:NO];
[myTextField setEditable:NO];
在“使可编辑”的操作中,我正在执行此操作:
[myTextField setSelectable:YES];
[myTextField setEditable:YES];
问题是:
当 myTextField 中没有光标或有光标但用户未键入时,它工作正常其中的任何内容并单击 - “使不可编辑”,然后 myTextField 变得不可编辑,但是当它有光标并且用户在其中输入内容后单击“使不可编辑”时,他/她仍然可以编辑 myTextField。
对于其解决方案,我尝试在用户单击“使其不可编辑”按钮后立即从 myTextField 中删除光标,方法是在可选择和可编辑语句之前添加这些行:
[someOtherTextField selectText:self];
[[NSRunLoop currentRunLoop] 执行选择器:@selector(selectText:) 一些其他文本字段 论据:自我 订单:9999 模式:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
[someOtherTextField成为FirstResponder];
但没有一个适用于我 :(
有人能建议一些解决方案吗?
I am trying to do a simple task:
I have an editable text field, two buttons (titles: make editable/ make un-editable) over a window. Idea is: when user clicks "make editable" button, text field should become editable and when he/she clicks "make un-editable", it should become un-editable.
In action of "make un-editable" I am doing this:
[myTextField setSelectable:NO];
[myTextField setEditable:NO];
and in action of "make editable" I am doing this:
[myTextField setSelectable:YES];
[myTextField setEditable:YES];
Problem is:
It works fine when myTextField does not have cursor within it or it has cursor but user does not type anything in it and clicks - "make un-editable", then myTextField becomes un-editable but when it has cursor and user clicks "make un-editable" after typing something within it he/she can still edit myTextField.
For its solution I tried to remove cursor from myTextField as soon as user clicks "make un-editable" button, by adding these lines before selectable and editable statements:
[someOtherTextField selectText:self];
[[NSRunLoop currentRunLoop]
performSelector:@selector(selectText:)
someOtherTextField
argument:self
order:9999
modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];[someOtherTextField becomeFirstResponder];
but none is working for me :(
Can anyone suggest some solution for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
becomeFirstResponder
的文档说我不确定隐藏文本字段是否可以成为第一响应者,所以请尝试:
[[myTextField 窗口] makeFirstResponder: nil]
The docs for
becomeFirstResponder
sayI'm not sure if a hidden text field can become first responder, so try:
[[myTextField window] makeFirstResponder: nil]
在 swift 5 中
使用以下代码
in swift 5
use bellow code