【问题标题】:Add a label after a String在字符串后添加标签
【发布时间】:2019-12-10 19:13:14
【问题描述】:

我需要用两种颜色创建一行文本

会有一个文本,它是黑色的字符串,会有一个 $ 符号,它应该是红色的。

lazy var dollarSmb: UILabel = {
      let smb = UILabel()
      smb.text = "$"
      smb.font = UIFont.systemFont(ofSize: 17, weight: .regular)
      smb.textColor = UIColor.red
      smb.baselineAdjustment = .alignCenters
      smb.translatesAutoresizingMaskIntoConstraints = false
      return smb
   }()

我想在标签字符串之后添加它,类似这样:

Var label = "This is a test" + " \(dollarSmb)"

没有用

谁能帮助我最好的方法? 非常感谢

【问题讨论】:

  • 使用NSAttributedString 在一个字符串中使用不同的颜色和字体。

标签: swift string uilabel


【解决方案1】:

您可以使用NSAttributedString 构造一个具有不同颜色的字符串。

let attributedString = NSMutableAttributedString(string: "This is a test ")
let dollarSymbl = NSAttributedString(string: "$", attributes: [.foregroundColor: UIColor.red])
attributedString.append(dollarSymbl)

// Then assign it to a UILabel
label.attributedText = attributedString

【讨论】:

    【解决方案2】:

    使用NSAttributedString,而不是设置smb.text,而是设置smb.attributedText

    类似

    smb.attributedText = NSAttributedString(string: "$", attributes [.foregroundColor: UIColor.red])
    

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多