简体   繁体   中英

Font change on selecting NSTextField

I am wanting to create a simple label with an attributed string. I do this like this:

NSDictionary *noNotificationsAttrs = [NSDictionary dictionaryWithObjectsAndKeys:centredStyle,
                                      NSParagraphStyleAttributeName,
                                      [NSFont fontWithName:@"Raleway-Bold" size:30],
                                      NSFontAttributeName,
                                      _grey,
                                      NSForegroundColorAttributeName,
                                      nil];
NSMutableAttributedString *noNotificationsString =
[[NSMutableAttributedString alloc] initWithString:@"No Notifications"
                                       attributes:noNotificationsAttrs];

NSTextField* title_field = [[NSTextField alloc] initWithFrame:
                             CGRectMake(
                                        0,
                                        0,
                                        200,
                                        200
                                        )
                             ];
[title_field setWantsLayer:true];
[title_field setSelectable:YES];
[title_field setAllowsEditingTextAttributes:true];
[title_field setAttributedStringValue:noNotificationsString];
[title_field setEditable:false];
[title_field setBordered:false];
title_field.tag = 1;

Which turns out like this:

在此输入图像描述

and

在此输入图像描述

Unfortunately when clicking (selecting) this label it appears like this:

在此输入图像描述

and

在此输入图像描述

Which is a bit bolder and pixelated around the corners. This is happening with lots of other labels with different strings, sizes and colours. How can I fix it?!

Please note these labels are nested inside nsscrollview -> nstableview -> viewForTableColumn


Stack on selection:

在此输入图像描述 I believe the problem is that NSCell calls an edit function on mousedown.


The font is also different on selection!! 在此输入图像描述


Edit:

Interestingly if I remove wantslayer:YES from the (2) parent view it does not do this. But they both need wantslayer or else I can't have curved corners etc...

Add this line to your code.

NSTextView *textEditor = (NSTextView *)[[[NSApplication sharedApplication] keyWindow] fieldEditor:YES forObject:title_field];

[textEditor setSelectedTextAttributes:noNotificationsAttrs];

Thus adding the attributes to NSTextView associated with window while selection.

What you're getting now like bold and font changes after selection will get overrided.

Edit:

Working code

Have changed NSForegroundColorAttributeName to NSBackgroundColorAttributeName and _grey to [NSColor clearColor]

NSDictionary *noNotificationsAttrs = [NSDictionary dictionaryWithObjectsAndKeys:centredStyle,
                                      NSParagraphStyleAttributeName,
                                      [NSFont fontWithName:@"Raleway-Bold" size:30],
                                      NSFontAttributeName,
                                      [NSColor clearColor],
                                      NSBackgroundColorAttributeName,
                                      nil];

To fix this I made a custom NSTextField where on select it updates like this:

- (void)textViewDidChangeSelection:(NSNotification *)a{
    [self setNeedsDisplay:YES];
    [self setNeedsLayout:YES];
    [self.superview setNeedsLayout:YES];
    [self.superview setNeedsDisplay:YES];
}

but still acts funny some times

I had fixed it perfect! hope to help everyone.

1.lazy property
- (NSTextField *)textFieldOne{
    if (!_textFieldOne) {
        _textFieldOne = ({
            NSTextField *view = [[NSTextField alloc]init];

            view.cell.scrollable = true;

            view.font = [NSFont fontWithName:@"PingFangSC-Light" size:14];
            view.cell.wraps = true;

            view.editable = false;
            view.selectable = true;
            view.allowsEditingTextAttributes = true;
            if (@available(macOS 10.12.2, *)) {
                view.automaticTextCompletionEnabled = true;
            } else {
                // Fallback on earlier versions
            }
            view;
        });
    }
    return _textFieldOne;
}

2.
// @{string: url}
NSDictionary *dic = @{
                      @"github/shang1219178163": @"https://github.com/shang1219178163",
                          };
  self.textFieldOne.stringValue = [NSString stringWithFormat:@"%@\n%@\n%@", NSApplication.appName, NSApplication.appCopyright, @"github/shang1219178163"];
 [self.textFieldOne setHyperlinkDic:dic];


3.
#import "NSTextField+Helper.h"

-(void)setHyperlinkDic:(NSDictionary *)dic{
    // both are needed, otherwise hyperlink won't accept mousedown
    NSTextField *textField = self;
    NSDictionary * attributes = @{
                                  NSFontAttributeName: textField.font,
                                  };

    __block NSMutableAttributedString *mattStr = [[NSMutableAttributedString alloc]initWithString:textField.stringValue attributes:attributes];
    [dic enumerateKeysAndObjectsUsingBlock:^(NSString * key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSURL *url = [NSURL URLWithString:obj];
        NSAttributedString * attStr = [NSAttributedString hyperlinkFromString:key withURL:url font:textField.font];
        NSRange range = [mattStr.string rangeOfString:key];
        [mattStr replaceCharactersInRange:range withAttributedString:attStr];

    }];
    textField.attributedStringValue = mattStr;

    textField.cell.wraps = true;
    textField.cell.scrollable = true;
    textField.editable = false;
    textField.selectable = true;
    textField.allowsEditingTextAttributes = true;

}

4.
#import "NSAttributedString+Helper.h"

+(id)hyperlinkFromString:(NSString *)string withURL:(NSURL *)aURL font:(NSFont *)font{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString: string];

    NSRange range = NSMakeRange(0, attrString.length);

//    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc]init];
    NSDictionary * dic = @{
                           NSFontAttributeName: font,
                           NSForegroundColorAttributeName: NSColor.blueColor,
                           NSLinkAttributeName: aURL.absoluteString,
                           NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),
//                           NSParagraphStyleAttributeName: paraStyle,
//                           NSBaselineOffsetAttributeName: @15,
                           };


    [attrString beginEditing];
    [attrString addAttributes:dic range:range];
    [attrString endEditing];
    return attrString;
}

display

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM