焦点上的NSTextField的selectText [英] selectText of NSTextField on focus

查看:67
本文介绍了焦点上的NSTextField的selectText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以建议一种方法,当用户单击它时选择NSTextField的所有文本吗?

Could anybody suggest a method to select all the text of an NSTextField when the user clicks it?

我确实找到了将NSTextField子类化然后再使用mouseDownfirstResponder的建议,但是,这超出了我的能力.因此,我希望要么有一个更简单的解决方案,要么某个人可能会友善地详细说明所需的步骤.

I did find suggestions to subclass NSTextField and then use mouseDown or firstResponder,` but it's beyond my skill for now. So I was hoping either there would be an easier solution or somebody might be kind enough to detail the steps required.

推荐答案

没有更简单的解决方案,您需要将NSTextField子类化以完成所需的操作.如果要在Cocoa中做任何有用的事情,您将需要学习如何处理子类化.

There isn't an easier solution, you need to subclass NSTextField to do what you want. You will need to learn how to handle subclassing if you are to do anything useful in Cocoa.

文本字段对于子类而言可能相对复杂,因为NSTextField使用称为字段编辑器的单独的NSTextView对象来处理实际的编辑.该文本视图由NSTextFieldNSWindow对象返回,并且可用于页面上的所有文本字段.

Text fields can be relatively complex to subclass because an NSTextField uses a separate NSTextView object called the Field Editor to handle the actual editing. This text view is returned by the NSWindow object for the NSTextField and it is re-used for all text fields on the page.

与任何NSResponder子类一样,NSTextField响应方法-acceptsFirstResponder-becomeFirstResponder.当窗口希望将焦点放在特定控件或视图上时,将调用这些方法.如果您从这两种方法中返回YES,则控件/视图将具有第一响应者状态,这意味着它是活动控件.但是,如上所述,NSTextField实际上在单击时为字段编辑器提供了第一响应者状态,因此您需要在NSTextField子类中执行类似的操作:

Like any NSResponder subclass, NSTextField responds to the methods -acceptsFirstResponder and -becomeFirstResponder. These are called when the window wants to give focus to a particular control or view. If you return YES from both these methods then your control/view will have first responder status, which means it's the active control. However, as mentioned, an NSTextField actually gives the field editor first responder status when clicked, so you need to do something like this in your NSTextField subclass:

@implementation MCTextField
- (BOOL)becomeFirstResponder
{
    BOOL result = [super becomeFirstResponder];
    if(result)
        [self performSelector:@selector(selectText:) withObject:self afterDelay:0];
    return result;
}
@end

这首先调用-becomeFirstResponder的超类实现,它将实现管理字段编辑器的艰巨工作.然后,它调用-selectText:来选择该字段中的所有文本,但是在延迟0秒后才执行此操作,该延迟将一直延迟到下一次运行事件循环为止.这意味着将在完全配置字段编辑器之后进行选择.

This first calls the superclass' implementation of -becomeFirstResponder which will do the hard work of managing the field editor. It then calls -selectText: which selects all the text in the field, but it does so after a delay of 0 seconds, which will delay until the next run through the event loop. This means that the selection will occur after the field editor has been fully configured.

这篇关于焦点上的NSTextField的selectText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆