Cocoa中的超链接

时间:2009-06-11 08:23:54

标签: cocoa hyperlink

我正在使用XCode开发Mac应用程序。我需要添加一个导航到特定网站的超链接。我尝试使用一个按钮,但我需要知道当鼠标悬停在该按钮上时如何将光标更改为手持光标。

3 个答案:

答案 0 :(得分:8)

我相信您可以使用不可编辑的NSTextField来显示网址。如果在您设置为字段值属性的NSAttributedString上正确设置属性,它将显示为标准蓝色下划线并为您处理光标跟踪。 This Apple Q& A告诉您如何设置网址的属性。

答案 1 :(得分:4)

要设置光标,必须使用光标跟踪方法addCursorRect:cursor:。但是,您实际上只应该从resetCursorRects方法中调用该方法。如果你在任何其他时间这样做,它基本上可以保证被忽略。

所以这意味着你需要继承NSButton(或者你想要使用的任何NSView子类)并覆盖resetCursorRects来为整个视图调用addCursorRect:cursor: {{1 }}

答案 2 :(得分:2)

我想为接下来的任何一个人发现更新的答案。

我发现当我在Barry的回答中尝试Apple Q& A指定的解决方案时,我的标签链接的文本在点击时会缩小。经过一些调试后,我发现Apple的文章中的示例代码设置了一个新的属性字符串,但并没有保留标签控件上的任何原始属性。解决方案是简单地从标签的原始属性字符串的副本开始,添加新的超链接属性,然后更新标签。

我做了一个简单的辅助函数,将NSTextField标签转换为超链接。它基本上整合了Apple页面上的解决方案,而无需为NSAttributeString添加类别扩展。

// Converts an otherwise plain NSTextField label into a hyperlink
-(void)updateControl:(NSTextField*)control withHyperlink:(NSString*)strURL
{
    // both are needed, otherwise hyperlink won't accept mousedown
    [control setAllowsEditingTextAttributes: YES];
    [control setSelectable: YES];

    NSURL* url = [NSURL URLWithString:strURL];

    NSAttributedString* attrString = [control attributedStringValue];

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

    [attr addAttribute:NSLinkAttributeName value:url range:range];
    [attr addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:range ];
    [attr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:range];

    [control setAttributedStringValue:attr];
}

然后调用它,在窗口初始化时将NSTextField和url字符串传递给它:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    [self updateControl:_label withHyperlink:@"http://www.stackoverflow.com"];

}