iOS6、7、8、9新特性总汇和适配说明 (14)

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];

[attributedString addAttribute:NSLinkAttributeName

                         value:@"username://marcelofabri_"

                         range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];

 

 

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],

                                 NSUnderlineColorAttributeName: [UIColor lightGrayColor],

                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

 

// assume that textView is a UITextView previously created (either by code or Interface Builder)

textView.linkTextAttributes = linkAttributes; // customizes the appearance of links

textView.attributedText = attributedString;

textView.delegate = self;

 

[Format Time: 0.0039 seconds]

这样就可以让链接在文本中显示。然而,你也可以控制当链接被点击的时候会发生什么,实现这个可以使用UITextViewDelegate协议的新的shouldInteractWithURL方法,就像这样:

Crayon Syntax Highlighter v2.7.1

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

    if ([[URL scheme] isEqualToString:@"username"]) {

        NSString *username = [URL host];

        // do something with this username

        // ...

        return NO;

    }

    return YES; // let the system open this URL

}

1

2

3

4

5

6

7

8

9

 

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwgywp.html