【问题标题】:NSTextField : How to draw background only when focusedNSTextField:如何仅在聚焦时绘制背景
【发布时间】:2011-05-24 07:45:13
【问题描述】:

我在窗口中放置了一个文本字段,并且我希望文本字段仅在获得焦点时绘制背景。 我知道窗口中的所有控件共享一个字段编辑器。 我尝试了子类 nstextfield 并实现了 becomeFirstResponder 和 resignFirstResponder。 并尝试对窗口使用自定义单例编辑器。

有人知道如何实现吗?


在 NSWindow 中,每个 textfield 或 button 共享一个字段编辑器实例(一个单例 NSTextView 实例),因此当您单击 textfield 时,textfield 首先成为 firstResponser,然后快速将其传递给共享字段编辑器。所以当textfield失去焦点时,永远不会调用textfield的resignFirstResponder(因为现在的field editor是FirstResponder)。

您可以查看 NSWindow API 中的 fieldEditor:forObject:。 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/fieldEditor:forObject:


解决方案: (谢谢,迈克尔·戈尔巴赫) 在我的窗口控制器中

- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject
{
    NSText *text = [sender fieldEditor:YES forObject:self];
    if(text&&[anObject isKindOfClass:[MyCustomTextField class]])
    {
        [text setBackgroundColor:[NSColor whiteColor]];
        [text setDrawsBackground:YES];
    }
    return text;
}

【问题讨论】:

    标签: cocoa nstextfield


    【解决方案1】:

    我最近刚刚在 tableView 中做了这个。您需要使用自定义单元格和 fieldEditor。具体来说,您需要在作为字段编辑器的NSText/NSTextView 对象上调用setDrawsbackground:YES,并调用setBackground: 来配置您选择的颜色。有两个地方可以设置自定义字段编辑器。

    一种是在您已配置NSTextField 使用的自定义NSTextFieldCell 子类上实现setUpFieldEditorAttributes:,另一种是使用窗口或窗口委托方法windowWillReturnFieldEditor:toObject:

    请注意,如果第一种方法不适用于特定设置,有时您需要使用第二种方法,因为它在代码路径中更早。

    【讨论】:

    • 稍后我会试试的。非常感谢。
    • 方法setUpFieldEditorAttributes在哪里?我找不到那个。
    • 啊,找到了(点击添加评论后...)是NSTextFieldCell类的方法
    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    相关资源
    最近更新 更多