objective-c - 将可点击的 URL 添加到我的 Cocoa View - 我做错了吗?

标签 objective-c cocoa nsattributedstring

我需要在我的 View 中动态设置可点击 URL 的文本和值。

我已经使用 NSTextView 让它工作,但设置字体似乎非常复杂,而且我不知道如何使文本居中:

NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"Click me"
                                                                               attributes:[[NSDictionary alloc] initWithObjectsAndKeys:[NSFont fontWithName:@"Lucida Grande" size:14], NSFontAttributeName, nil]];
[attrString beginEditing];
[attrString addAttribute:NSLinkAttributeName value:@"http://example.com" range:NSMakeRange(0, [attrString length])];
[attrString endEditing];
[[self.downloadLinkTextField textStorage] setAttributedString:attrString];
  1. 我做错了吗?我在 URL 对象库中找不到任何内容。
  2. 是否可以将链接居中对齐?

最佳答案

你做对了。苹果有一个 handy writeup about this它在 NSAttributedString 上提供了一个 Hyperlink 类别,如果您愿意,可以使用它。它们的类别还会对链接文本进行下划线和着色。

至于居中,这是 View 的功能,而不是文本本身的功能。您可以使用-[NSText alignCenter:] (NSTextNSTextView 的父类(super class)),在使用 setSelectedRange: 选择字符串后,或者如果您希望 View 中的所有文本居中,只需使用:

[myTextView setAlignment:NSCenterTextAlignment];

关于objective-c - 将可点击的 URL 添加到我的 Cocoa View - 我做错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6039792/

相关文章:

ios - 将 NSString 从空格剪切到末尾

cocoa - 网页 View 空白但内容在那里

ios - 如何使 UILabel 中的特定单词可选(Swift 2.0)?

ios - Swift:如何创建带有彩色 block 矩形背景的文本

ios - Objective-C - 如何从 NSAttributedString 创建 rtf

iOS 在@selector 处获取 UIButton 当前的 UIControlEventType

ios - 核心蓝牙 - 在后台执行长期操作

iphone - cocoa 服务器问题

objective-c - 10.8中如何显示文件复制进度

ios - 替代iOS消息传递的“层”消息传递框架