Изменить цвет ссылки в NSMutableAttributedString

У меня есть следующий код, но мои ссылки всегда синие. Как изменить их цвет?

[_string addAttribute:NSLinkAttributeName value:tag range:NSMakeRange(position, length)];
[_string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:(12.0)] range:NSMakeRange(position, length)];
[_string addAttribute:NSStrokeColorAttributeName value:[UIColor greenColor] range:NSMakeRange(position, length)];

_string — это NSMutableAttributedString, и позиция и длина работают нормально.


person cdub    schedule 06.02.2015    source источник
comment
Я использовал это: stackoverflow.com/questions/25457131/   -  person cdub    schedule 06.02.2015


Ответы (5)


Быстрый

Обновлено для Swift 4.2

Используйте linkTextAttributes с UITextView

textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]

И в контексте:

let attributedString = NSMutableAttributedString(string: "The site is www.google.com.")
let linkRange = (attributedString.string as NSString).range(of: "www.google.com")
attributedString.addAttribute(NSAttributedString.Key.link, value: "https://www.google.com", range: linkRange)
let linkAttributes: [NSAttributedString.Key : Any] = [
    NSAttributedString.Key.foregroundColor: UIColor.green,
    NSAttributedString.Key.underlineColor: UIColor.lightGray,
    NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]

// textView is a UITextView
textView.linkTextAttributes = linkAttributes
textView.attributedText = attributedString

Цель-C

Используйте linkTextAttributes с UITextView

textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor greenColor]};

Источник: этот ответ

И из этого сообщения:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
                         value:@"username://marcelofabri_"
                         range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];


NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],
                                 NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                 NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

// assume that textView is a UITextView previously created (either by code or Interface Builder)
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
textView.delegate = self;
person Suragch    schedule 26.08.2015
comment
Я смог изменить цвет ссылки, но как я могу изменить цвет, который появляется, когда вы продолжаете нажимать на ссылку? - person Mago Nicolas Palacios; 13.10.2017
comment
Идеально, но быстро 4.4 Используйте textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor.rawValue: UIColor.green] - person Kudos; 14.05.2021

Цвет ссылки — это цвет оттенка метки/текстового представления. Таким образом, вы можете изменить его, изменив цвет оттенка представления. Однако это не сработает, если вам нужны разные цвета ссылок в одном и том же представлении.

person crcalin    schedule 30.10.2015
comment
У меня работает на iOS 12. - person Iris Veriris; 26.04.2019
comment
Хорошо работает для UITextView - person DeepBlue; 10.07.2019
comment
Не работает в Xcode 11.2.1, Swift 5 для UILabel @crcalin - person ios; 11.03.2020
comment
@ios просто использует вместо этого UITextView, он работает с ним - person imike; 30.05.2021

Свифт

 let str = "By using this app you agree to our Terms and Conditions and Privacy Policy"
 let attributedString = NSMutableAttributedString(string: str)
 var foundRange = attributedString.mutableString.rangeOfString("Terms and Conditions")

 attributedString.addAttribute(NSLinkAttributeName, value: termsAndConditionsURL, range: foundRange)
 foundRange = attributedString.mutableString.rangeOfString("Privacy Policy")
 attributedString.addAttribute(NSLinkAttributeName, value: privacyURL, range: foundRange)
 policyAndTermsTextView.attributedText = attributedString
 policyAndTermsTextView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.blueColor()]
person Dasoga    schedule 16.02.2017

 NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:@"here" attributes:@{ @"myCustomTag" : @(YES), NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont fontWithName:@"SourceSansPro-Semibold" size:15], NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) }];

Цель-C

Это сделает подчеркнутый белый текст кликабельным. Выберите необходимые атрибуты для вашего кода и используйте его.

Чтобы иметь строку с кликабельной ссылкой, выполните следующие действия:

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Click " attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont fontWithName:@"SourceSansPro-Semibold" size:15]}];
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:@"here" attributes:@{ @"myCustomTag" : @(YES), NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont fontWithName:@"SourceSansPro-Semibold" size:15], NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) }];
[string appendAttributedString:attributedString];

В результате вы получите строку «Нажмите здесь», а «здесь» будет ссылкой. Вы можете установить разные стили для каждой строки.

person Victorianec    schedule 06.02.2015

Для Swift3.0

  override func viewDidLoad() {
     super.viewDidLoad()

  let linkAttributes = [
        NSLinkAttributeName: NSURL(string: "http://stalwartitsolution.co.in/luminutri_flow/terms-condition")!
        ] as [String : Any]
  let attributedString = NSMutableAttributedString(string: "Please tick box to confirm you agree to our Terms & Conditions, Privacy Policy, Disclaimer. ")

  attributedString.setAttributes(linkAttributes, range: NSMakeRange(44, 18))

  attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(value: 1), range: NSMakeRange(44, 18))

  textview.delegate = self
  textview.attributedText = attributedString
  textview.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.red]
  textview.textColor = UIColor.white
  }


  func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    return true
   }
person Maulik Patel    schedule 06.04.2018