Create tap-able “links” in the NSAttributedString of a UILabel?

前端 未结 30 2641
半阙折子戏
半阙折子戏 2020-11-22 02:07

I have been searching this for hours but I\'ve failed. I probably don\'t even know what I should be looking for.

Many applications have text and in this text are web

30条回答
  •  花落未央
    2020-11-22 03:03

    As I mentioned in this post, here is a light-weighted library I created specially for links in UILabel FRHyperLabel.

    To achieve an effect like this:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.

    use code:

    //Step 1: Define a normal attributed string for non-link texts
    NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
    
    label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
    
    
    //Step 2: Define a selection handler block
    void(^handler)(FRHyperLabel *label, NSString *substring) = ^(FRHyperLabel *label, NSString *substring){
        NSLog(@"Selected: %@", substring);
    };
    
    
    //Step 3: Add link substrings
    [label setLinksForSubstrings:@[@"Lorem", @"Pellentesque", @"blandit", @"Maecenas"] withLinkHandler:handler];
    

提交回复
热议问题