尝试与NSTextField创建链接

时间:2010-04-03 05:45:45

标签: cocoa hyperlink nstextfield clickable

我正在使用此类别(是吗?)http://www.nightproductions.net/references/dsclickableurltextfield_reference.html#setAttributedStringValue

实现可点击的文本字段。我已经在我的控制器类中导入了头文件,并像这样设置了它的属性字符串值

NSAttributedString* str = [[NSAttributedString alloc] initWithString:@"http://www.yahoo.com"];
[url setAttributedStringValue:(NSAttributedString *)str];

[str release];

文本字段不可选且不可编辑。

设置了文本字段值,但它不可点击,而且不是链接。

提前致谢。

1 个答案:

答案 0 :(得分:9)

我找到了另一种在NSTextField中显示链接的简单方法。您可以使用HTML。这是一个简短的例子:

-(NSAttributedString *)stringFromHTML:(NSString *)html withFont:(NSFont *)font
{
  if (!font) font = [NSFont systemFontOfSize:0.0];  // Default font
  html = [NSString stringWithFormat:@"<span style=\"font-family:'%@'; font-size:%dpx;\">%@</span>", [font fontName], (int)[font pointSize], html];
  NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
  NSAttributedString* string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:nil];
  return string;
}

现在您可以调用文本字段的方法:

// @property IBOutlet NSTextField *tf;
[tf setAllowsEditingTextAttributes: YES];
[tf setSelectable:YES];
NSString *credits = @"Visit our <a href=\"http://www.webpage.com\">webpage</a>";
[tf setAttributedStringValue:[self stringFromHTML:credits withFont:[tf font]]];
相关问题