【问题标题】:Adding font size and custom font name to attributed string in UITextView将字体大小和自定义字体名称添加到 UITextView 中的属性字符串
【发布时间】:2018-04-01 09:08:50
【问题描述】:

我有以下代码将属性字符串添加到 UITextView 文本。我需要快速添加自定义字体和字体大小。怎么做?

    func setAttributedString(string: String) -> NSAttributedString {
    let attrString = NSMutableAttributedString(string: string)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 7
    paragraphStyle.minimumLineHeight = 7
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSRange(location: 0, length:attrString.length))
    attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 30), range: NSRange(location: 0, length:attrString.length))
    return attrString
  }

我需要将自定义字体和字体大小添加到以下函数中。如何做到这一点?

【问题讨论】:

标签: ios swift3 uitextview nsattributedstring


【解决方案1】:

在 Swift 3 中

let attributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!, 
              NSAttributedStringKey.foregroundColor: UIColor.white]

let attributedString  = NSMutableAttributedString(string: "Your string" , attributes: attributes)

【讨论】:

    【解决方案2】:

    使用初始化器 init(string:attributes:)

    https://developer.apple.com/documentation/foundation/nsattributedstring/1408136-init

    let attrString = NSMutableAttributedString(string: string, attributes:
                [NSFontAttributeName:UIFont(
                name: "Georgia",
                size: 18.0)!])
        //Add more attributes here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 2019-01-31
      相关资源
      最近更新 更多