首页 > 解决方案 > 如何在文本的同一部分添加下划线和链接属性?

问题描述

我有一个 UITextView,想在文本中添加一些带下划线的链接,代码如下:

    subText.text = NSLocalizedString("VC_COMMON_SUBSCRIBE_FULL_TEXT", comment: "")
    let theString = subtext.attributedText?.mutableCopy(with: nil) as! NSMutableAttributedString
    let tcRange = theString.mutableString.range(of: NSLocalizedString("VC_COMMON_SUBSCRIBE_TERMS_TEXT", comment: ""))
    let ppRange = theString.mutableString.range(of: NSLocalizedString("VC_COMMON_SUBSCRIBE_PRIVACY_TEXT", comment: ""))
    theString.addAttribute(NSLinkAttributeName, value: Config.termsAndConditionsURL(), range: tcRange)
    theString.addAttribute(NSLinkAttributeName, value: Config.privacyPolicyURL(), range: ppRange)
    theString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: tcRange)
    theString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: ppRange)
    subtext.attributedText = theString

这段代码的问题是,当运行包含链接的文本部分时不可见(尽管链接是可选择的,即使它的文本看不到)如果我注释掉链接属性并只使用下划线属性,然后文本按预期显示带有下划线。为什么添加链接属性会导致文本不显示?

我尝试使用 UILabel 而不是 UITextView 并正确显示,但是在这种情况下链接不起作用,即使 UILabel 已将 userInteractionEnabled 设置为 true。

标签: iosswift

解决方案


我用自己的字符串替换了本地化字符串,用虚拟链接替换了链接。此代码正确显示文本视图:

let subText = UITextView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
subText.text = NSLocalizedString("These are the terms. This is our privacy policy", comment: "")
let theString = subText.attributedText?.mutableCopy(with: nil) as! NSMutableAttributedString
let tcRange = theString.mutableString.range(of: NSLocalizedString("terms", comment: ""))
let ppRange = theString.mutableString.range(of: NSLocalizedString("privacy policy", comment: ""))
theString.addAttribute(NSAttributedStringKey.link, value: "https://google.com", range: tcRange)
theString.addAttribute(NSAttributedStringKey.link, value: "https://google.com", range: ppRange)
theString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: tcRange)
theString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: ppRange)
subText.attributedText = theString

来自操场快速浏览的图像:

在此处输入图像描述

看来您正在使用像NSUnderlineStyleAttributeName. 它们已被重命名为NSAttributedStringKey.underlineStyle等等。


推荐阅读