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

前端 未结 30 3043
半阙折子戏
半阙折子戏 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 02:51

    I created UILabel subclass named ResponsiveLabel which is based on textkit API introduced in iOS 7. It uses the same approach suggested by NAlexN. It provides flexibility to specify a pattern to search in the text. One can specify styles to be applied to those patterns as well as action to be performed on tapping the patterns.

    //Detects email in text
    
     NSString *emailRegexString = @"[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
     NSError *error;
     NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:emailRegexString options:0 error:&error];
     PatternDescriptor *descriptor = [[PatternDescriptor alloc]initWithRegex:regex withSearchType:PatternSearchTypeAll withPatternAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
     [self.customLabel enablePatternDetection:descriptor];
    

    If you want to make a string clickable, you can do this way. This code applies attributes to each occurrence of the string "text".

    PatternTapResponder tapResponder = ^(NSString *string) {
        NSLog(@"tapped = %@",string);
    };
    
    [self.customLabel enableStringDetection:@"text" withAttributes:@{NSForegroundColorAttributeName:[UIColor redColor],
                                                                     RLTapResponderAttributeName: tapResponder}];
    

提交回复
热议问题