2009-06-11 39 views
5

我正在XCode中开发Mac应用程序。我需要添加一个导航到特定站点的超链接。我用一个按钮试过,但我需要知道如何将鼠标移动到该按钮上时将光标更改为手形光标。Cocoa中的超链接

回答

8

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

+0

这个Apple技术笔记唯一的问题是鼠标光标仍然会变成鼠标移过来的工字型文本输入样式光标。 – 2012-04-30 19:46:33

4

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

因此,这意味着你需要继承NSButton(或任何你想使用NSView子类),并覆盖resetCursorRects呼吁addCursorRect:cursor:整个视图的bounds

+0

为我工作很好,谢谢。我已经分类了NSTextField。 – 2016-11-14 14:40:19

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"]; 

}