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

前端 未结 30 2613
半阙折子戏
半阙折子戏 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:54

    based on Charles Gamble answer, this what I used (I removed some lines that confused me and gave me wrong indexed) :

    - (BOOL)didTapAttributedTextInLabel:(UILabel *)label inRange:(NSRange)targetRange TapGesture:(UIGestureRecognizer*) gesture{
        NSParameterAssert(label != nil);
    
        // create instances of NSLayoutManager, NSTextContainer and NSTextStorage
        NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
        NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
    
        // configure layoutManager and textStorage
        [textStorage addLayoutManager:layoutManager];
    
        // configure textContainer for the label
        NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(label.frame.size.width, label.frame.size.height)];
    
        textContainer.lineFragmentPadding = 0.0;
        textContainer.lineBreakMode = label.lineBreakMode;
        textContainer.maximumNumberOfLines = label.numberOfLines;
    
        // find the tapped character location and compare it to the specified range
        CGPoint locationOfTouchInLabel = [gesture locationInView:label];
        [layoutManager addTextContainer:textContainer]; //(move here, not sure it that matter that calling this line after textContainer is set
    
        NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInLabel
                                                               inTextContainer:textContainer
                                      fractionOfDistanceBetweenInsertionPoints:nil];
        if (NSLocationInRange(indexOfCharacter, targetRange)) {
            return YES;
        } else {
            return NO;
        }
    }
    

提交回复
热议问题