这让我发疯了,我无法在任何地方找到一个简单直接的答案,说明如何在Swift 4 中使用自定义字体使文本范围加粗、下划线。
我去的每一页都有一部分信息,但它以螺旋形的方式向我发送。我找到了 Swift 3 的下划线方法,不包括自定义字体,下一个说在 Swift 4 中使用粗体字体自定义版本等,但不包括下划线。非常令人沮丧。
所以。我有这个文字
重置密码邮件已发送。没收到?重新发送
“再次发送”需要加粗并加下划线。它是一个完整的字符串,在一个 UILabel 中。
很确定新方法使用 UIAttributedStringKey。
我知道公平很简单,这就是为什么我发现它令人沮丧并且对它失去了耐心。
哦,我目前使用的是 iOS 11,XCode 9.4.1。我可能会在接下来的几天内更新。
提前致谢
编辑
嘿dfd,感谢您的评论。这基本上是我得到的代码(在 swift 4.0 中没用,尽管在 Swift 3.0 中工作几乎就像我记得以前使用的代码一样。
我必须在某处声明字体,而且我也没有找到粗体的代码,但我确实有一些用于范围和下划线的代码。
干杯
var text = self.completeText.text
let textRange = NSMakeRange(50, (text?.count)!)
let attributedText = NSMutableAttributedString(string: text!)
let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
attributedText.addAttribute(underlineAttribute)
*最终编辑*
这是工作代码。
let label = self.completeText
let labelString = self.completeText.text
let attributedText = NSMutableAttributedString(string: labelString!)
let rangeToUnderline = (labelString! as NSString).range(of: "Send again")
attributedText.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: rangeToUnderline)
我将使用这些属性添加 OpenSansBold 自定义字体,它应该可以正常工作。
谢谢阿德里安,谢谢其他人的建议。非常感激!
PS 我不认为有人对 Swift 4.1 上的属性字符串有很好的参考?会好的。
如果您没有看到 Open Sans,那是一个单独的问题。为了强调它,您将使用NSMutableAttributedString(而不是 NSAttributedString)。
以下是您在字符串的一部分下划线的方式:
let label = UILabel()
let labelString = "Didn’t get it? Send again"
let attributedText = NSMutableAttributedString(string: labelString)
let rangeToUnderline = (labelString as NSString).range(of: "Send again")
attributedText.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: rangeToUnderline)
至于将字符串的一部分加粗,您可以这样做。我懒得追踪字体名称,测试它等,所以我会让你填写粗体空白和粗体和非粗体之间切换背后的逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句