在UITextView中将字体大小和自定义字体名称添加到属性字符串

时间:2017-10-05 18:26:02

标签: ios swift3 uitextview nsattributedstring

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

    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
  }

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

2 个答案:

答案 0 :(得分:0)

在Swift 3中

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

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

答案 1 :(得分:0)

使用初始化程序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