I have been trying to underline on hover a NSTextField. I what happened with my first attempt was that the text was underlined, but it went on top of the previous text. With another attempt, it become increasingly bold.
-(void)mouseEntered:(NSEvent *)theEvent {
if (is_underlined)
return;
is_underlined = YES;
//NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
//NSMutableAttributedString * as = [[NSMutableAttributedString alloc] initWithString:self.event.label
// attributes:attrsDictionary];
//[as autorelease];
NSMutableAttributedString * as = [[[self attributedStringValue] mutableCopy] autorelease];
[as beginEditing];
[as addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
range:[[[self window] fieldEditor:YES forObject:self] selectedRange]];
[as endEditing];
[self setAttributedStringValue:as];
}
-(void)mouseExited:(NSEvent *)theEvent {
if (!is_underlined)
return;
is_underlined = NO;
// self.stringValue = self.event.label;
//[self setAttributedStringValue:nil];
NSMutableAttributedString * as = [[[self attributedStringValue] mutableCopy] autorelease];
[as beginEditing];
[as removeAttribute:NSUnderlineStyleAttributeName range:[[[self window] fieldEditor:YES forObject:self] selectedRange]];
// [as addAttribute:NSUnderlineStyleAttributeName
// value:[NSNumber numberWithInt:0]
// range:[[[self window] fieldEditor:YES forObject:self] selectedRange]];
[as endEditing];
[self setAttributedStringValue:as];
}
I think that I have found the answer – it lies not in the code itself, but in the code the demo code that I was building off of. The author implemented these views in drawRect which meant that each time the rectangle was drawn, a new textfield was created in the same location.