ios - 如何在文本的同一部分添加下划线和链接属性?
问题描述
我有一个 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。
解决方案
我用自己的字符串替换了本地化字符串,用虚拟链接替换了链接。此代码正确显示文本视图:
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
等等。
推荐阅读
- c - 在 C 中将静态大小的向量与静态大小的常量非方阵相乘的最快方法,生成一个 15 元素的输出向量
- javascript - 如何在“for in”循环中获取对象?
- python - 如何从doc文件中提取文本?
- arrays - Laravel 验证 - 通过自定义规则相互验证关联数组值
- python - 将具有透明背景的图像与普通图像(非透明背景)混合后如何调整 alpha 值?
- python - C++ 中类似 Python 的迭代器习惯用法
- html - 如何在谷歌云存储桶中删除静态网站的 .html 扩展名
- python - 如何播种 scipy.stats.norm.rvs 并让它使用 PCG64 BitGenerator?
- json - 结合 DjangoObjectType 和 ObjectType - Django, GraphQL
- wget - 谁能教我安装 wget 到 git bash