objective-c - NSTextField 光标仅在第二次鼠标输入时更改

标签 objective-c cocoa nstextfield

从昨天开始,我就试图让 NSTextField 表现得像超文本。我几乎已经达到了我的目标,但我仍然有一个奇怪的错误。 我将 NSTextField 子类化以覆盖 mouseEntered: 和 mouseExited:。在这些方法中,我在 NSTextField 中的文本下划线并将 NSCursor 更改为 pointingHandCursor。

奇怪的是,每次都会弹出下划线,而光标更改似乎只能在第二次鼠标输入时起作用:。第一次不会出现。

它似乎与我的子类有关,而不是与环境有关,因为如果我将其中两个 NSTextField 放置在我的 View 中,则它们仅在我第二次将鼠标放在其上时才显示光标。

这是我在子类中使用的代码:

- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        NSTrackingAreaOptions option = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
        NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect:self.bounds options:option owner:self userInfo:nil];
        [self addTrackingArea:area];
    }
    return self;
}

- (void) mouseEntered:(NSEvent *)theEvent
{
    [self addCursorRect:self.bounds cursor:[NSCursor pointingHandCursor]];

    if (!self.undelineText)
    {
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:self.stringValue];
        NSRange range = NSMakeRange(0, [attrString length]);
        [attrString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:range];
        self.undelineText = attrString;
    }
    [self setAttributedStringValue:self.undelineText];
}

- (void) mouseExited:(NSEvent *)theEvent
{
    if (!self.normalText)
    {
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:self.stringValue];
        self.normalText = attrString;
    }
    [self setAttributedStringValue:self.normalText];
}

希望你能帮助我。

最佳答案

您是否尝试过将 NSTrackingArea 代码放入 awakeOnNib 函数中? 所以它看起来像这样:

- (void)awakeFromNib
{
  NSTrackingAreaOptions option = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow;
  NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect:self.bounds options:option owner:self userInfo:nil];
  [self addTrackingArea:area];
}

关于objective-c - NSTextField 光标仅在第二次鼠标输入时更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24591703/

相关文章:

iphone - 日期排序的 NSArray

cocoa - 更改 NSWindow 标题栏的颜色

ios - NSString 没有名为 bridgeToObjectiveC 的成员

objective-c - iOS 中的__weak 和__strong 属性有什么区别?

cocoa - 如何使用红色窗口按钮检测我的窗口正在关闭?

cocoa - 使用 Swift 和自动布局变得更高的 NSTextField

swift - 如何在计时器工作时设置 NSTextField 值?

macos - Swift/OSX - 在定制的 NSSecureTextField 上禁用聚焦环

ios - 如何获取定位服务的准确授权状态?

ios - 在部分代码中抑制 "is partial: introduced in iOS"