在UILabel.attributedText中建立链接*不是*蓝色,*不是*带下划线

时间:2013-03-13 09:12:25

标签: ios objective-c xcode nsattributedstring

我希望我的OHAttributedLabel中的一些单词是链接,但我希望它们是蓝色以外的颜色,我不想要下划线。

这给了我一个带下划线文字的蓝色链接:

 -(void)createLinkFromWord:(NSString*)word withColor:(UIColor*)color atRange:(NSRange)range{

    NSMutableAttributedString* mutableAttributedText = [self.label.attributedText mutableCopy];   

    [mutableAttributedText beginEditing];
    [mutableAttributedText addAttribute:kOHLinkAttributeName
                   value:[NSURL URLWithString:@"http://www.somewhere.net"]
                   range:range];

    [mutableAttributedText addAttribute:(id)kCTForegroundColorAttributeName
                   value:color
                   range:range];

    [mutableAttributedText addAttribute:(id)kCTUnderlineStyleAttributeName
                   value:[NSNumber numberWithInt:kCTUnderlineStyleNone]
                   range:range];
    [mutableAttributedText endEditing];


    self.label.attributedText = mutableAttributedText;

}

由于我正在使用OHAttributedLabel,我也尝试使用其NSAttributedString+Attributes.h类别中的方法,但这些方法也返回蓝色下划线链接:

-(void)createLinkFromWord:(NSString*)word withColor:(UIColor*)color atRange:(NSRange)range{

NSMutableAttributedString* mutableAttributedText = [self.label.attributedText mutableCopy];

[mutableAttributedText setLink:[NSURL URLWithString:@"http://www.somewhere.net"] range:range];
[mutableAttributedText setTextColor:color range:range];
[mutableAttributedText setTextUnderlineStyle:kCTUnderlineStyleNone range:range];

self.label.attributedText = mutableAttributedText;
}

如果我注释掉设置每个版本中的链接的行,那么文本就会变成我传入的内容 - 这是有效的。看起来好像设置链接会覆盖它并将其重新变为蓝色。

不幸的是,我发现的苹果文档页面显示了如何将链接文本设置为蓝色并为其加下划线,这正是我不需要的: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/AttributedStrings/Tasks/ChangingAttrStrings.html

11 个答案:

答案 0 :(得分:61)

所以我最终使用了TTTAttributedLabel:

-(void)createLinkFromWord:(NSString*)word withColor:(UIColor*)color atRange:(NSRange)range{
    NSMutableAttributedString* newTextWithLinks = [self.label.attributedText mutableCopy];
    NSURL *url = [NSURL URLWithString:@"http://www.reddit.com"];
    self.label.linkAttributes = @{NSForegroundColorAttributeName: color, 
                                   NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)};
    [self.label addLinkToURL:url withRange:range];
}

我发现OHAttributedLabel实际上有方法来设置链接并为这些链接声明颜色和下划线样式。但是,我希望链接基于参数是不同的颜色。 TTTAttributedLabel允许您为自己创建的每个链接设置linkAttributes属性,从而允许这样做。

答案 1 :(得分:23)

我正在使用TTTAttributedLabel。我想改变链接文本的颜色,并保持下划线。 Pim的答案看起来很棒,但对我来说不起作用。这是做了什么工作:

label.linkAttributes = @{ (id)kCTForegroundColorAttributeName: [UIColor magentaColor],
                           (id)kCTUnderlineStyleAttributeName : [NSNumber numberWithInt:NSUnderlineStyleSingle] };

注意:如果您不希望文本带下划线,则从字典中删除kCTUnderlineStyleAttributeName键。

答案 2 :(得分:22)

这是我改进版的Ramsel已经很好的答案。 我相信它更具可读性,我希望它能得到很好的使用。

label.linkAttributes = @{ NSForegroundColorAttributeName: [UIColor whiteColor],
                          NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };

这是a list of other attibute names

答案 3 :(得分:8)

如果您使用 UITextView ,则可能需要更改tintColor属性以更改链接颜色。

答案 4 :(得分:6)

TTTAttributedLabel的Swift 2.3示例:

yourLabel.linkAttributes       = [
    NSForegroundColorAttributeName: UIColor.grayColor(),
    NSUnderlineStyleAttributeName: NSNumber(bool: true)
]
yourLabel.activeLinkAttributes = [
    NSForegroundColorAttributeName: UIColor.grayColor().colorWithAlphaComponent(0.8),
    NSUnderlineStyleAttributeName: NSNumber(bool: false)
]

Swift 4

yourLabel.linkAttributes = [
    .foregroundColor: UIColor.grayColor(),
    .underlineStyle: NSNumber(value: true)
]
yourLabel.activeLinkAttributes = [
    .foregroundColor: UIColor.grayColor().withAlphaComponent(0.7),
    .underlineStyle: NSNumber(value: false)
]

答案 5 :(得分:2)

如果您像我一样,并且真的不想使用TTT(或者需要在您自己的自定义实现中使用它,而您正在以其他奇怪的方式进行绘制):

首先,子类NSLayoutManager,然后重写如下:

sys_id

这或多或少告诉布局管理器实际上是从您的属性字符串始终尊重- (void)showCGGlyphs:(const CGGlyph *)glyphs positions:(const CGPoint *)positions count:(NSUInteger)glyphCount font:(UIFont *)font matrix:(CGAffineTransform)textMatrix attributes:(NSDictionary *)attributes inContext:(CGContextRef)graphicsContext { UIColor *foregroundColor = attributes[NSForegroundColorAttributeName]; if (foregroundColor) { CGContextSetFillColorWithColor(graphicsContext, foregroundColor.CGColor); } [super showCGGlyphs:glyphs positions:positions count:glyphCount font:font matrix:textMatrix attributes:attributes inContext:graphicsContext]; } ,而不是Apple内部对于链接的怪异。

如果您需要做的就是获得可以正确绘制(根据我的需要)的布局管理器,则可以在此处停止。如果您实际上需要一个UILabel,那很痛苦,但有可能。

再次,首先,在所有这些方法中将UILabel子类化并拍击。

NSForegroundColorAttributeName

Shamelessly taken from here。尽力而为地在原始作者方面进行工作。

答案 6 :(得分:0)

TTTAttributedLabel的Swift 3示例:

yourLabel.linkAttributes = [
    NSForegroundColorAttributeName: UIColor.green,  
    NSUnderlineStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleNone.rawValue)
]
yourLabel.activeLinkAttributes = [
    NSForegroundColorAttributeName: UIColor.green,  
    NSUnderlineStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleDouble.rawValue)
]

答案 7 :(得分:0)

对于使用int MaxSubSlow(){ int max_so_far = 0,i,j,k,temp_sum; for(j=1;j<N;j++){ for(k=j;k<N;k++){ temp_sum = 0; for(i=j;i<k;i++){ temp_sum += A[i]; } if(temp_sum > max_so_far){ max_so_far = temp_sum; } } } return max_so_far; }

的Swift 3
TTTAttributedLabel

答案 8 :(得分:0)

对于Swift 3,以下方式使用TTTAttributedLabel

为我解决了问题

1)在故事板上添加标签,并将其类定义为TTTAttributedLabel Storyboard view

2)在代码中定义 @IBOutlet var termsLabel: TTTAttributedLabel!

3)然后在ViewDidLoad中写下这些行

termsLabel.attributedText = NSAttributedString(string: "By using this app you agree to the Privacy Policy & Terms & Conditions.")
guard let labelString = termsLabel.attributedText else {
            return
        }
        guard let privacyRange = labelString.string.range(of: "Privacy Policy") else {
            return
        }
        guard let termsConditionRange = labelString.string.range(of: "Terms & Conditions") else {
            return
        }

        let privacyNSRange: NSRange = labelString.string.nsRange(from: privacyRange)
        let termsNSRange: NSRange = labelString.string.nsRange(from: termsConditionRange)

        termsLabel.addLink(to: URL(string: "privacy"), with: privacyNSRange)
        termsLabel.addLink(to: URL(string: "terms"), with: termsNSRange)

        termsLabel.delegate = self
        let attributedText = NSMutableAttributedString(attributedString: termsLabel.attributedText!)
        attributedText.addAttributes([NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 12)!], range: termsNSRange)
        attributedText.addAttributes([NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 12)!], range: privacyNSRange)
        attributedText.addAttributes([kCTForegroundColorAttributeName as String: UIColor.orange], range: termsNSRange)
        attributedText.addAttributes([kCTForegroundColorAttributeName as String: UIColor.green], range: privacyNSRange)
        attributedText.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleNone.rawValue], range: termsNSRange)
        attributedText.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleNone.rawValue], range: privacyNSRange)
        termsLabel.attributedText = attributedText

看起来像这样 Simulator View

4)最后编写TTTAttributedLabel的委托功能,以便您可以点击

打开链接
public func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
    switch url.absoluteString  {
    case "privacy":
        SafariBrowser.open("http://google.com", presentingViewController: self)
    case "terms":
        SafariBrowser.open("http://google.com", presentingViewController: self)
    default:
        break
    }
}

Swift 4.2的更新

对于Swift 4.2,步骤3中有一些更改,所有其他步骤将保持与上述相同:

3)在ViewDidLoad中写下这些行

termsLabel.attributedText = NSAttributedString(string: "By using this app you agree to the Privacy Policy & Terms & Conditions.")
guard let labelString = termsLabel.attributedText else {
            return
        }
        guard let privacyRange = labelString.string.range(of: "Privacy Policy") else {
            return
        }
        guard let termsConditionRange = labelString.string.range(of: "Terms & Conditions") else {
            return
        }

        let privacyNSRange: NSRange = labelString.string.nsRange(from: privacyRange)
        let termsNSRange: NSRange = labelString.string.nsRange(from: termsConditionRange)

        termsLabel.addLink(to: URL(string: "privacy"), with: privacyNSRange)
        termsLabel.addLink(to: URL(string: "terms"), with: termsNSRange)

        termsLabel.delegate = self
        let attributedText = NSMutableAttributedString(attributedString: termsLabel.attributedText!)
        attributedText.addAttributes([NSAttributedString.Key.font : UIFont(name: "Roboto-Regular", size: 12)!], range: termsNSRange)
        attributedText.addAttributes([NSAttributedString.Key.font : UIFont(name: "Roboto-Regular", size: 12)!], range: privacyNSRange)
        attributedText.addAttributes([kCTForegroundColorAttributeName as NSAttributedString.Key : UIColor.orange], range: termsNSRange)
        attributedText.addAttributes([kCTForegroundColorAttributeName as NSAttributedString.Key : UIColor.green], range: privacyNSRange)
    attributedText.addAttributes([NSAttributedString.Key.underlineStyle: 0], range: termsNSRange)
        attributedText.addAttributes([NSAttributedString.Key.underlineStyle: 0], range: privacyNSRange)

答案 9 :(得分:0)

Swift 4.0:

简短

 let LinkAttributes = NSMutableDictionary(dictionary: testLink.linkAttributes)
 LinkAttributes[NSAttributedStringKey.underlineStyle] =  NSNumber(value: false)
 LinkAttributes[NSAttributedStringKey.foregroundColor] = UIColor.black // Whatever your label color
 testLink.linkAttributes = LinkAttributes as NSDictionary as! [AnyHashable: Any]

答案 10 :(得分:-1)

UITextView 与&#34; Link&#34;一起使用会更好。功能启用。在这种情况下,您可以使用一行:

Swift 4

// apply link attributes to label.attributedString, then
textView.tintColor = UIColor.red // any color you want

完整示例:

    let attributedString = NSMutableAttributedString(string: "Here is my link")
    let range = NSRange(location: 7, length:4)
    attributedString.addAttribute(.link, value: "http://google.com", range: range)
    attributedString.addAttribute(.underlineStyle, value: 1, range: range)
    attributedString.addAttribute(.underlineColor, value: UIColor.red, range: range)
    textView.tintColor = UIColor.red // any color you want

或者您只能将属性应用于链接:

  textView.linkTextAttributes = [
      .foregroundColor: UIColor.red
      .underlineStyle: 1,
      .underlineColor: UIColor.red
   ]