[macOS开发]NSTextField实现蓝色字体及下划线

问题

如何改变NSTextField文字带下划线?
如何改变NSTextField文字颜色为蓝色?
如何只改变NSTextField部分文字为蓝色且带下划线?

最终效果

image.png

解决方案

    //标签文字都是蓝色且带下划线
    NSMutableAttributedString *linkAttrStr = [[NSMutableAttributedString alloc] initWithString:_label1.stringValue];
    [linkAttrStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, linkAttrStr.length)];
    [linkAttrStr addAttribute:NSForegroundColorAttributeName value:[NSColor linkColor] range:NSMakeRange(0, linkAttrStr.length)];
    [_label1 setAttributedStringValue:linkAttrStr];
    
    //只有"click here"文字是蓝色且带下划线
    NSRange range = [_label2.stringValue rangeOfString:@"click here"];
    linkAttrStr = [[NSMutableAttributedString alloc] initWithString:_label2.stringValue];
    [linkAttrStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:range];
    [linkAttrStr addAttribute:NSForegroundColorAttributeName value:[NSColor linkColor] range:range];
    [_label2 setAttributedStringValue:linkAttrStr];

你可能感兴趣的:([macOS开发]NSTextField实现蓝色字体及下划线)