2014-02-07 78 views
2

我使用drawInRect:動態構建視圖並在其上打印屬性文本。一些文字可能包含網頁鏈接。如何檢測網頁鏈接上的點擊,以便我可以在UIWebView中加載鏈接?我沒有使用UILabel,UITextView或UITextField來顯示文本,因爲文本包含文本和圖像的混合。在NSAttributedString中檢測鏈接上的水龍頭

這是繪製文本的我的UIView子類的drawRect中的一些代碼。

//draw the text 

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:self.message.text]; 

    [attString beginEditing]; 

    NSArray *arrString = [attString.string componentsSeparatedByString:@" "]; 
    for (NSString *str in arrString) 
    { 
     if ([str rangeOfString:@"http://" options:NSCaseInsensitiveSearch].location != NSNotFound || 
      [str rangeOfString:@".com" options:NSCaseInsensitiveSearch].location != NSNotFound || 
      [str rangeOfString:@".gov" options:NSCaseInsensitiveSearch].location != NSNotFound || 
      [str rangeOfString:@".org" options:NSCaseInsensitiveSearch].location != NSNotFound || 
      [str rangeOfString:@".edu" options:NSCaseInsensitiveSearch].location != NSNotFound || 
      [str rangeOfString:@".net" options:NSCaseInsensitiveSearch].location != NSNotFound || 
      [str rangeOfString:@".xxx" options:NSCaseInsensitiveSearch].location != NSNotFound) 
     { 
      NSRange rng = [attString.string rangeOfString:str]; 

      NSString *url; 

      if ([str rangeOfString:@"http://" options:NSCaseInsensitiveSearch].location == NSNotFound && 
       [str rangeOfString:@"https://" options:NSCaseInsensitiveSearch].location == NSNotFound) 
      { 
       url = [NSString stringWithFormat:@"http://%@", str]; 
      } 
      else 
      { 
       url = str; 
      } 

      [attString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:url] range:rng]; 
     } 
    } 

    [attString endEditing]; 

    CGSize theSize; 
    theSize = [attString.string sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(CHAT_TEXT_WIDTH, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping]; 
    [[UIColor blackColor] set]; 
    CGRect textRect = CGRectMake(0, 0, theSize.width, theSize.height); 
    textRect.origin.x += 10; 
    textRect.origin.y += 10; 

    if (self.type == MESSAGE_BOX_RECEIVE) { 
     textRect.origin.x += ARROW_WIDTH; 
    } 

    [attString drawInRect:textRect]; 

感謝您的幫助......

+0

這可能給你一些想法。 http://stackoverflow.com/questions/13888941/nsattributedstring-tappable-ios – sangony

+0

你可以發佈你的代碼?我可以提出一些想法,但這取決於您的自定義視圖的工作方式。 – WolfLink

+0

@WolfLink我編輯了我的帖子以包含我如何繪製文本的代碼。謝謝。 – SeanT

回答

3

你想要做什麼是繪製TextKit文本(iOS中7中引入)。這使您可以通過TextKit來解釋水龍頭。

下面是一個可下載的例子項目中,我顯示的單詞列表,並檢測用戶敲擊哪個字上(我甚至通過短暫突出字迴應):

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch10p543drawingWithTextKit/ch23p815attributedStringDrawing3/StyledText.swift

+0

你能更新這個鏈接嗎?這是404。 –

+0

@DougSmith你想把它移動到原來的位置,還是你想要更新的iOS 8/Swift版本的例子? – matt

+0

iOS 8/Swift版本會很棒。 –

相關問題