【问题标题】:Trying to create link with NSTextField尝试使用 NSTextField 创建链接
【发布时间】:2023-03-18 08:27:01
【问题描述】:

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

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

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

[str release];

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

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

提前致谢。

【问题讨论】:

    标签: cocoa hyperlink nstextfield clickable


    【解决方案1】:

    我找到了另一种在 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]]];
    

    【讨论】:

    • 这样更好,因为光标会变成手指光标,而另一种方法是点击时字体会发生变化。
    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    相关资源
    最近更新 更多