【问题标题】:How to change font in the string only for the last two characters如何仅更改字符串中最后两个字符的字体
【发布时间】:2020-01-17 18:03:06
【问题描述】:

我有字符串 0.1234 要查找最后两个字符,我使用 string.suffix(2) 如果我使用 NSRange 在属性字符串中找到这个范围,它会很好地工作,直到字符串不具有等于值。如果字符串类似于 1.1212,nsrange 将应用于第一个找到的值(在这种情况下为 string.suffix(2) = 12) 所以格式会出错。

如何仅更改最后两个字符的字体。

【问题讨论】:

  • 确保你的字符串至少有 2 个字符并且它确实将字符串 endIndex 偏移了 -2
  • 正如@leo 所说,长度为 2 的后缀具有索引 end-2。您还可以使用长度、前缀和后缀来获得这两个部分...
  • 这个问题其实和NSAttributedString没什么关系,全是简单的子串计算。
  • @NRitH 如何更改字符串中最后两个字符的字体而不使其归属?

标签: swift range nsattributedstring nsrange nsmutableattributedstring


【解决方案1】:

您可以使用此扩展程序

extension String {
    func attributedStringWithColorSize( color: UIColor, size:CGFloat = 12) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: self)


        if self.count < 3 {
            return attributedString
        }
            let range = NSRange(location: self.count-2, length: 2)
            attributedString.addAttribute(NSAttributedString.Key.font,value: UIFont.systemFont(ofSize: size) , range: range)
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)

        return attributedString
    }
}

这样使用

@IBOutlet weak var lab: UILabel!
    override func viewDidLoad() {

        lab.attributedText = "1.1470".attributedStringWithColorSize(color: UIColor.red , size: 15)
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

【讨论】:

    【解决方案2】:

    你可以使用String.Index方法

    func index(_ i: String.Index, offsetBy n: String.IndexDistance, limitedBy limit: String.Index) -> String.Index?
    

    在您的 string.endIndex 上,负偏移量为 2 并受您的 string.startIndex 限制:


    let string = "1.1212"
    if let start = string.index(string.endIndex, offsetBy: -2, limitedBy: string.startIndex) {
        print(string[start..<string.endIndex])  // "12\n"
        // or using a partial range
        print(string[start...]) // "12\n"
    }
    

    应用较小的字体大小和颜色,保留原始标签字体:

    游乐场测试:

    let string = "1.1212"
    let label = UILabel(frame: .zero)
    label.attributedText = NSAttributedString(string: string)
    
    if let start = string.index(string.endIndex, offsetBy: -2, limitedBy: string.startIndex), let attrStr = label.attributedText {
        let mutableAttributedString = NSMutableAttributedString(attributedString: attrStr)
        mutableAttributedString.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: label.font.withSize(label.font.pointSize * 0.6)], range: .init(start..<string.endIndex, in: string))
        label.attributedText = mutableAttributedString
        label.sizeToFit()
    }
    

    【讨论】:

    • 在这种情况下如何更改最后两个字体?
    • 我只看到一种解决方案来制作两个具有不同字体的 uilabels
    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 2016-04-25
    • 2014-04-21
    • 2017-02-22
    • 2014-02-12
    • 1970-01-01
    • 2020-06-02
    • 2016-01-21
    相关资源
    最近更新 更多