单击时TextField中的NSAttributedString更改/重置

 星宿 发布于 2023-01-08 13:59

我正在关注苹果的这个指南,但它并没有真正起作用.

基本上,我正在尝试通过自定义WindowController类向窗口中的NSTextField添加超链接.我能够让超链接处理一些问题:

当我将鼠标悬停在超链接上时,我会得到一个'I bean'(指示您可以选择文本的光标).我想要一只通常出现在超链接上的手

当我单击超链接文本时,它会在浏览器中成功打开链接,但随后会更改文本大小和格式(例如,它不再居中,返回默认值).现在,当我将鼠标悬停在它上面时,我得到了一只手.

经过一些实验,我发现最初的字符串格式(例如大小,我点击它之前的字体)是我创建标签的.xib文件的格式.点击之后,它变成了一些默认字体,我似乎无法以任何方式影响.但是超链接仍然存在.

这是一些代码:

AboutWindowController.h

#import "AboutWindowController.h"

@interface AboutWindowController ()

@end

@implementation AboutWindowController

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    [self.testLabel setAllowsEditingTextAttributes:YES];
    [self.testLabel setSelectable:YES];

    NSMutableAttributedString* string1 = [[NSMutableAttributedString alloc] init];

    NSString* inString = @"Apple Computer";
    NSURL* aURL = [NSURL URLWithString:@"www.google.com"];

    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: inString];
    NSRange range = NSMakeRange(0, [attrString length]);

    [attrString beginEditing];
    [attrString addAttribute:NSLinkAttributeName value:[aURL absoluteString] range:range];

    // make the text appear in blue
    [attrString addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:range];

    // next make the text appear with an underline
    [attrString addAttribute:
     NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSSingleUnderlineStyle] range:range];

    [attrString endEditing];


    [string1 appendAttributedString:  attrString];


    [self.testLabel setAttributedStringValue:string1];
    [self.testLabel setFont:[NSFont fontWithName:@"Helvetica" size:20]];
}
@end

AboutWindowController.h

#import 

@interface AboutWindowController : NSWindowController
@property (weak) IBOutlet NSTextField *testLabel;

@end

.xib非常简单:它是一个带有标签的窗口,我将标签正确链接到.h文件(我相信)

谢谢您的帮助.我会尝试定期回来回答任何问题/澄清.编辑:请检查我对bikram答案的评论,以了解我的情况.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有