如何更改 UILabel 中链接的颜色?

Gru*_*kes 4 ios swift

我想更改 UILabel 中链接的颜色。我发现了很多关于如何为 UITextView 执行此操作的过去问题,以及过去在 Obj-C 中有答案的问题(但无法将这些转换为 Swift,因为 Obj-c 中确实存在的属性不再执行,例如 NSMutableAttributedString .linkTextAttributes 例如)。但是我找不到如何为 UILabel 和 Swift 4 执行此操作。

Iur*_*nea 12

对于默认NSAttributedString.Key。链接颜色将为蓝色。
如果您需要自定义链接颜色,您可以将属性设置为NSAttributedString.Key。附件而不是.link并像这样设置前景色和下划线颜色:

let linkCustomAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14),
                            NSAttributedString.Key.foregroundColor: UIColor.red,
                            NSAttributedString.Key.underlineColor: UIColor.magenta,
                            NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
                            NSAttributedString.Key.attachment: URL(string: "https://www.google.com")] as [NSAttributedString.Key : Any]
Run Code Online (Sandbox Code Playgroud)

如果您需要处理链接的触摸,您可以使用此自定义标签类:

import UIKit

public protocol UILabelTapableLinksDelegate: NSObjectProtocol {
    func tapableLabel(_ label: UILabelTapableLinks, didTapUrl url: String, atRange range: NSRange)
}

public class UILabelTapableLinks: UILabel {

    private var links: [String: NSRange] = [:]
    private(set) var layoutManager = NSLayoutManager()
    private(set) var textContainer = NSTextContainer(size: CGSize.zero)
    private(set) var textStorage = NSTextStorage() {
        didSet {
            textStorage.addLayoutManager(layoutManager)
        }
    }

    public weak var delegate: UILabelTapableLinksDelegate?

    public override var attributedText: NSAttributedString? {
        didSet {
            if let attributedText = attributedText {
                textStorage = NSTextStorage(attributedString: attributedText)
                findLinksAndRange(attributeString: attributedText)
            } else {
                textStorage = NSTextStorage()
                links = [:]
            }
        }
    }

    public override var lineBreakMode: NSLineBreakMode {
        didSet {
            textContainer.lineBreakMode = lineBreakMode
        }
    }

    public override var numberOfLines: Int {
        didSet {
            textContainer.maximumNumberOfLines = numberOfLines
        }
    }

    public override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    private func setup() {
        isUserInteractionEnabled = true
        layoutManager.addTextContainer(textContainer)
        textContainer.lineFragmentPadding = 0
        textContainer.lineBreakMode = lineBreakMode
        textContainer.maximumNumberOfLines  = numberOfLines
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        textContainer.size = bounds.size
    }

    private func findLinksAndRange(attributeString: NSAttributedString) {
        links = [:]
        let enumerationBlock: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void = { [weak self] value, range, isStop in
            guard let strongSelf = self else { return }
            if let value = value {
                let stringValue = "\(value)"
                strongSelf.links[stringValue] = range
            }
        }
        attributeString.enumerateAttribute(.link, in: NSRange(0..<attributeString.length), options: [.longestEffectiveRangeNotRequired], using: enumerationBlock)
        attributeString.enumerateAttribute(.attachment, in: NSRange(0..<attributeString.length), options: [.longestEffectiveRangeNotRequired], using: enumerationBlock)
    }

    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let locationOfTouch = touches.first?.location(in: self) else {
            return
        }
        textContainer.size = bounds.size
        let indexOfCharacter = layoutManager.glyphIndex(for: locationOfTouch, in: textContainer)
        for (urlString, range) in links where NSLocationInRange(indexOfCharacter, range) {
            delegate?.tapableLabel(self, didTapUrl: urlString, atRange: range)
            return
        }            
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的代码中设置标签:

customLabel.attributedText = <<Your attributed text with custom links>>
customLabel.delegate = self
Run Code Online (Sandbox Code Playgroud)

实现委托:

extension YourClass: UILabelTapableLinksDelegate {
    func tapableLabel(_ label: UILabelTapableLinks, didTapUrl url: String, atRange range: NSRange) {
        print("didTapUrl: ", url)
    }
}
Run Code Online (Sandbox Code Playgroud)