Trying to create a link with NSTextField

I use this category (right?) Http://www.nightproductions.net/references/dsclickableurltextfield_reference.html#setAttributedStringValue

to create interactive text fields. I imported the header file into my controller class and set its attribute string value similar to this

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

[str release];

The text field is not selected or edited.

The value of the text field is set, but it is not clickable, and it is not a link.

Thanks in advance.

+5
source share
1 answer

I found another easy way to show links in an NSTextField. You can use HTML. Here is a quick example:

-(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]]];
+9

All Articles