2016-01-28 9 views
8

HTMLから生成されたNSAttributedStringにはいくつかのリンクが含まれています。属性付き文字列は、UITextViewに表示されます。私は、リンクに異なるフォントスタイルを適用し、これにはlinkTextAttributesを設定したいと思います。私はNSForegroundColorAttributeName,NSFontAttributeNameNSUnderlineStyleAttributeNameを追加しました。何らかの理由で前景色が適用されますが、残りの属性は適用されません。UITextView linkTextAttributesフォント属性がNSAttributedStringに適用されていません

myTextView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.redColor(), NSFontAttributeName : textLinkFont, NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleNone.rawValue] 

は、誰がこれを直面しているとどのように私は、元のHTMLにインラインCSSを適用しなくても、リンク用のフォントスタイルを変更できますか?ありがとう。

答えて

16

フォント名にlinkTextAttributesが機能しない理由がわかりません。しかし、NSAttributedStringのリンク属性を更新することでこれを達成できます。以下のコードを確認してください。

 do { 
     let htmlStringCode = "For more info <a href=\"http://www.samplelink.com/subpage.php?id=8\">Click here</a>" 

     let string = try NSAttributedString(data: htmlStringCode.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil) 

     let newString = NSMutableAttributedString(attributedString: string) 
     string.enumerateAttributesInRange(NSRange.init(location: 0, length: string.length), options: .Reverse) { (attributes : [String : AnyObject], range:NSRange, _) -> Void in 
      if let _ = attributes[NSLinkAttributeName] { 
       newString.removeAttribute(NSFontAttributeName, range: range) 
       newString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(30), range: range) 
      } 
     } 
     textField.attributedText = newString 
     textField.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.redColor(), NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleNone.rawValue] 

    }catch { 
    } 

これは、このために目的-Cコードです:enumerateAttributesInRange:で文字列を起因後処理が私のために動作しませんいくつかの理由

NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType}; 
NSData *data = [html dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO]; 

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil]; 
NSMutableAttributedString *attributedStringWithBoldLinks = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString]; 

[attributedString enumerateAttributesInRange:NSMakeRange(0, attributedString.string.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) { 

    if ([attrs objectForKey:NSLinkAttributeName]) { 
     [attributedStringWithBoldLinks removeAttribute:NSFontAttributeName range:range]; 
     [attributedStringWithBoldLinks addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"YourFont-Bold" size:16.0] range:range]; 
    } 
}]; 

self.linkTextAttributes = @{NSForegroundColorAttributeName : [UIColor redColor]}; 

self.attributedText = attributedStringWithBoldLinks; 

Screenshot

+0

目的を果たします。しかし、 'linkTextAttributes'で動作する属性のリストがあるなら、私は知りたいです! – lostInTransit

2

私はNSDataDetectorを使用してリンクを検出し、enumerateMatchesInString:options:range:usingBlock:を使用して、文字列のすべてのリンクに対して自分のスタイルを設定しました。あなただけのhtmlコード内のスタイルを追加することができます - あなたはHTMLを使用する場合は、テキストのスタイルを適用する簡単な方法もあります

+ (void) postProcessTextViewLinksStyle:(UITextView *) textView { 
    NSAttributedString *attributedString = textView.attributedText; 
    NSMutableAttributedString *attributedStringWithItalicLinks = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString]; 

    NSError *error = nil; 
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink 
                  error:&error]; 

    [detector enumerateMatchesInString:[attributedString string] 
          options:0 
          range:NSMakeRange(0, [attributedString length]) 
         usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ 
          NSRange matchRange = [match range]; 
          NSLog(@"Links style postprocessing. Range (from: %lu, length: %lu)", (unsigned long)matchRange.location, (unsigned long)matchRange.length); 
          if ([match resultType] == NSTextCheckingTypeLink) {          
           [attributedStringWithItalicLinks removeAttribute:NSFontAttributeName range:matchRange]; 
           [attributedStringWithItalicLinks addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"YourFont-Italic" size:14.0f] range:matchRange]; 
          } 
         }]; 

    textView.attributedText = attributedStringWithItalicLinks; 
} 
+0

私の意見ではこれが好ましい答えです –

0

: はここに私の処理機能です。次に、テキストの属性を設定することについて心配する必要はありません。たとえば、次のように

NSString *html = [NSString stringWithFormat:@"<p style=\"font-family: Your-Font-Name; color: #344052; font-size: 15px\"><a style=\"color: #0A9FD2\" href=\"https://examplelink.com\">%@</a> %@ on %@</p>", name, taskName, timeString]; 
NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType}; 
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding]; 

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil]; 
1

これは、これは私がそれをHTML

guard let attributedString = errorTextView.attributedText else { 
    return 
} 
guard let font = UIFont.init(name: "Roboto-Regular", size: 15) else { 
    return 
} 
let newString = NSMutableAttributedString(attributedString: attributedString) 

let types: NSTextCheckingResult.CheckingType = [.link, .phoneNumber] 

guard let linkDetector = try? NSDataDetector(types: types.rawValue) else { return } 
let range = NSRange(location:0,length: attributedString.length) 

linkDetector.enumerateMatches(in: attributedString.string, options: [], range: range, using: { (match : NSTextCheckingResult?, 
    flags : NSRegularExpression.MatchingFlags, stop) in 

    if let matchRange = match?.range { 
     newString.removeAttribute(NSFontAttributeName, range: matchRange) 
     newString.addAttribute(NSFontAttributeName, value: font, range: matchRange) 
    } 
}) 
errorTextView.attributedText = newString 
を回避するので好む@CTiPKAへスウィフト3溶液での回答の迅速な3更新

guard let font = UIFont.init(name: "Roboto-Regular", size: 15) else { 
    return 
} 
let newString = NSMutableAttributedString(attributedString: string) 
let range = NSRange(location:0,length: string.length) 
string.enumerateAttributes(in: range, options: .reverse, using: { (attributes : [String : Any], range : NSRange, _) -> Void in 
    if let _ = attributes[NSLinkAttributeName] { 
     newString.removeAttribute(NSFontAttributeName, range: range) 
     newString.addAttribute(NSFontAttributeName, value: font, range: range) 
    } 
}) 
errorTextView.attributedText = newString 
errorTextView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.green, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue] 

@Arun Ammannayaから上にあります
1

単純なケースの場合:(ひどいHTMLを使用しないで):

let linkTextAttributes : [String : Any] = [ 
     NSForegroundColorAttributeName: UIColor.red, 
     NSUnderlineColorAttributeName: UIColor.magenta, 
     NSUnderlineStyleAttributeName: NSUnderlineStyle.patternSolid.rawValue 
    ] 

    self.infoText.linkTextAttributes = linkTextAttributes 
関連する問題