iOS7 textView處理URL鏈接 以及點擊 長按手勢的處理

舉例1 :文本超鏈接

@property (weak, nonatomic) IBOutlet UITextView *tv;


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

    [attributedString addAttribute:NSLinkAttributeName

                             value:@"username://marcelofabri_"

                             range:[[attributedString stringrangeOfString:@"@marcelofabri_"]];

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

                                     NSUnderlineColorAttributeName: [UIColor lightGrayColor],

                                     NSUnderlineStyleAttributeName@(NSUnderlinePatternSolid)};

    self.tv.linkTextAttributes = linkAttributes;

    self.tv.attributedText = attributedString;

    self.tv.delegate =self ;

    self.tv.editable = NO;


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

    NSLog(@"%@",URL.absoluteString);

    return NO ;

}

舉例2 :文本:系統默認是雙擊 ,這裏用單擊實現

    self.tv.dataDetectorTypes = UIDataDetectorTypeAll;

    self.tv.attributedText = [[NSAttributedString alloc]initWithString:

                               @" +8602980000000.\r\n"

                               "My personal web site www.xxxxxx.com.\r\n"

                               "My E-mail address is [email protected].\r\n"

                               "I was born in 1900-01-01."];

   self.tv.editable = NO;


  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onlyTap:)];

    [self.tv addGestureRecognizer:tap];




- (void)onlyTap:(UITapGestureRecognizer *)recognizer

{

    CGPoint location = [recognizer locationInView:self.tv];

    NSLog(@"Tap Gesture Coordinates: %.2f %.2f", location.x, location.y);

    NSString *tappedSentence = [self lineAtPosition:CGPointMake(location.x, location.y)];

    NSLog(@"%@",tappedSentence);


}


- (NSString *)lineAtPosition:(CGPoint)position

{

    //eliminate scroll offset

    position.y += _tv.contentOffset.y;

    //get location in text from textposition at point

    UITextPosition *tapPosition = [_tv closestPositionToPoint:position];

    //fetch the word at this position (or nil, if not available)

    UITextRange *textRange = [_tv.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularitySentence inDirection:UITextLayoutDirectionRight];

    return [_tv textInRange:textRange];

}




參考資料:

http://stackoverflow.com/questions/15034652/tap-gesture-to-part-of-a-uitextview

http://www.raywenderlich.com/48001/easily-overlooked-new-features-ios-7#textViewLinks







發佈了35 篇原創文章 · 獲贊 1 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章