简体   繁体   English

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

[英]Adding font size and custom font name to attributed string in UITextView

I have the following code to add the attributed string to the UITextView text. 我有以下代码将属性字符串添加到UITextView文本中。 I need to add the custom font and font size to it in swift. 我需要快速向其添加自定义字体和字体大小。 How to do it? 怎么做?

    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
  }

I need to add the custom font and font size to the following function. 我需要将自定义字体和字体大小添加到以下功能。 How to achieve this? 如何实现呢?

In Swift 3 在Swift 3中

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

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

Use the initializer init(string:attributes:) 使用初始化程序init(string:attributes :)

https://developer.apple.com/documentation/foundation/nsattributedstring/1408136-init 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM