0
我想從昨天開始使NSTextField行爲像超文本一樣。我幾乎達到了我的目標,但我仍然有一個奇怪的錯誤。 我將NSTextField重寫爲覆蓋mouseEntered:和mouseExited :.在這些方法中,我將NSTextField中的文本加下劃線,並將NSCursor更改爲pointingHandCursor。NSTextField光標僅在第二個鼠標上更改進入
奇怪的是,每當光標改變似乎只能從第二個mouseEntered:工作時,下劃線彈出。它不會第一次顯示。
它似乎與我的子類,而不是環境相關,因爲如果我將兩個NSTextField放在我的視圖中,它們都只在第二次將鼠標放在它上方時顯示光標。
這是我在子類中使用的代碼:
- (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];
}
我希望你能幫助我。