0

我需要在我的视图中动态设置可点击 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. 链接是否可以居中对齐?
4

2 回答 2

3

你做对了。Apple 对此有一个方便的文章,其中提供了一个Hyperlink类别NSAttributedString,如果您愿意,可以使用该类别。它们的类别还强调和着色链接文本。

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

[myTextView setAlignment:NSCenterTextAlignment];
于 2011-05-18T06:13:55.760 回答
1

此线程中缺少一些非常重要的内容:

在属性字符串的开始/结束编辑之后和设置属性字符串之前...

您需要在文本字段上调用以下内容,否则链接将不起作用:

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

我从这里收到了这些信息

哈哈!-埃里克

于 2013-07-08T21:37:38.830 回答