Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create link with NSTextField

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.

like image 314
Chris Avatar asked Apr 03 '10 05:04

Chris


1 Answers

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]]];
like image 109
Oleg Uryutin Avatar answered Sep 19 '22 05:09

Oleg Uryutin