【问题标题】:how to change format of substring in swift如何在swift中更改子字符串的格式
【发布时间】:2021-12-19 11:48:29
【问题描述】:

我从我的回复中收到一条消息,例如“您的账单是:10.00”

但我需要以粗体显示数字并且仅显示该数字(“:”之后的所有内容)。我知道我可以使用 SubString,但不完全了解如何拆分文本并正确格式化它

我的旧测试:

    self.disclaimerLabel.attributedText = String(format: my).htmlAttributedString(withBaseFont: Font.overlineRegular07.uiFont, boldFont: Font.overlineBold02.uiFont, baseColor: Color.blueyGreyTwo.uiColor, boldColor: Color.blueyGreyTwo.uiColor)

【问题讨论】:

  • 你的问题到底是什么,拆分字符串并提取数字部分或如何将属性应用于字符串?
  • 技术上两者都有,但我一开始是尝试选择文本,然后寻找格式化解决方案
  • 例如split(separator: ":") 怎么样或者找到“:”的索引并使用范围,这里有很多选项,哪个最好取决于您的要求。你自己试过什么?
  • 我正在尝试学习如何使用它,我添加的代码是在这个应用程序中他们正在格式化文本的一种方式,但只有当你单独获得一些信息时它才好,现在我从响应中得到一个完整的字符串,需要用粗体格式化“:”之后的内容

标签: swift string substring


【解决方案1】:

您可以将字符串拆分为 char :,然后您可以更改文本属性,例如:

var str = "your bill is: 10.00"

var splitArray = str.components(separatedBy: ":")

let normalText = NSMutableAttributedString(string: splitArray[0] + ":")    
let boldText = splitArray[1]

let boldTextAtr = NSMutableAttributedString(string: boldText, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0) ])

normalText.append(boldTextAtr)

let labell = UILabel()
labell.attributedText = normalText

labell.attributedText 会打印出你真正想要的内容

【讨论】:

  • 这样“:”被抹掉了,还有机会保留吗?
  • 已编辑 @biggreentree 。您可以手动将“:”添加到 normalText[ 的末尾
【解决方案2】:

为单个单词或短语添加样式的需求非常普遍,因此值得手头有一种方法来帮助您:

extension NSMutableAttributedString {
    func apply(attributes: [NSAttributedString.Key: Any], to targetString: String) {
        let nsString = self.string as NSString
        let range = nsString.range(of: targetString)
        guard range.length != 0 else { return }
        self.addAttributes(attributes, range: range)
    }
}

那么你唯一的问题是发现你想要应用属性的文本片段。如果您不知道它是 "10.00",那么正如您所知道的,您可以通过在冒号加空格处拆分字符串来查找。

【讨论】:

  • NSAttributedStringNSMutableAttributedString 扩展方法中是多余的。 Key 就足够了
  • @LeoDabus 风格在旁观者眼中。
【解决方案3】:

my 是如何构建的?如果来自 2 个部分,请在加入前为每个部分设置属性。

如果你得到my作为一个整体,你可以访问子字符串

let parts = my.split(separator: ":")

parts[1] 将是“你的账单是” 部分[2] 将是“10:00”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-25
    • 2021-04-02
    • 2016-09-15
    • 2023-03-29
    • 2018-07-09
    • 2016-02-21
    • 2018-01-19
    • 2014-09-15
    相关资源
    最近更新 更多