Trying to create link with NSTextField

Chris picture Chris · Apr 3, 2010 · Viewed 8k times · Source

I'm using this category (is that right?) http://www.nightproductions.net/references/dsclickableurltextfield_reference.html#setAttributedStringValue

to implement clickable textfields. I've imported the header file in my controller class and set it's attributed string value like this

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

[str release];

The text field is not selectable and not editable.

The text field value is set but it's not clickable and it's not a link.

Thanks in advance.

Answer

Aplextor picture Aplextor · Nov 15, 2012

I have found another easy way to show links in NSTextField. You can use HTML. Here is a short 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;
}

Now you can call the method for text field:

// @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]]];