问题
I would like to have an attributed string in a NSTextView
. The attributed string has 3 lines, each one a different color and no underline. I want to be able to click (or double click) on each line, which would print out the line number.
回答1:
You can use the addAttribute:value:range of NSMutableAttributeString to assign the click behaviour to your attributed string.
According to the documentation : Attributed String. When your string is clicked, it should call clickedOnLink:atIndex: of TextView class or textView:clickedOnLink:atIndex: in the TextView Delegate.
Like this (coded on the browser, beware of errors )
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithString: @"Clickable String"];
NSRange range = NSMakeRange(0, [str length]);
[str beginEditing];
[str addAttribute:NSLinkAttributeName value:@"The value of your attr String" range:range];
[str endEditing];
[textBox setAllowsEditingTextAttributes: YES];
[textBox setSelectable: YES];
[textBox setAttributedStringValue: str];
来源:https://stackoverflow.com/questions/6303485/nsattributedstring-clicks