如何在NSAttributedString上设置字体大小

时间:2017-08-30 12:01:34

标签: ios objective-c nsattributedstring

编辑 - 这已被标记为重复,但正如我在下面所述,我正在寻找一个Swift解决方案。我发现的一切都是用目标C写的。

我正在尝试将HTML转换为NSAttributedString,但无法确定如何设置字体样式和大小。所有示例都在Objective C中,我不熟练。如何将字体样式/大小设置为System 15(作为示例)

private func stringFromHtml(string: String) -> NSAttributedString? {
        do {
            let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
            if let d = data {
                let str = try NSAttributedString(data: d,
                                                 options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],                                                  documentAttributes: nil)
                return str
            }
        } catch {
        }
        return nil
    }
编辑......我已经尝试了几种方法。我无法让它发挥作用。我现在收到一条错误消息:表达式的类型不明确,没有更多的上下文。它指向NSAttributedString 我尝试过以下方法:

let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
  if let d = data {
     let str = try NSAttributedString(data: d,
                       attributes: myAttribute,
                       options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

7 个答案:

答案 0 :(得分:30)

INSERT INTO MTCT..HKSTF087.FUELCHARGES
       ([QTM_ID]
       ,[TITLECODE]
       ,[FUELCHARGERATE]
       ,[ISSPECIALRATE]
       ,[EFFECTIVEFROMDATE]
       ,[EFFECTIVETHRUDATE]
       ,[CREATEDBY]
       ,[CREATEDDATE]
       ,[UPDATEDBY]
       ,[UPDATEDDATE])
 VALUES
       (4446
       ,'ABCD'
       ,12
       ,0
       ,getdate()
       ,'2099-12-31 00:00:00.0000000'
       ,'system'
       ,getdate()
       ,null
       ,null)

<强>字体

  let myString = "Swift Attributed String"
  let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
  let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) 

  // set attributed text on a UILabel
  myLabel.attributedText = myAttrString

<强>影

 let myAttribute = [ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0)! ]

<强>下划线

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray
let myAttribute = [ NSShadowAttributeName: myShadow ]

<强> TEXTCOLOR

 let myAttribute = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue ]

BackGroud颜色

 let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

答案 1 :(得分:10)

Swift 4您可以使用:

 let stringWithAttribute = NSAttributedString(string: selectedFilter ?? "",
                                                  attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0)])

答案 2 :(得分:3)

检查此项以获取快速5:

extension String {
    func getAttributedString<T>(_ key: NSAttributedString.Key, value: T) -> NSAttributedString {
       let applyAttribute = [ key: T.self ]
       let attrString = NSAttributedString(string: self, attributes: applyAttribute)
       return attrString
    }
}

您可以在此处检查更多属性样式: https://developer.apple.com/documentation/foundation/nsattributedstring/key

使用

// Background Color
let attributedString = "YOUR_STRING".getAttributedString(.backgroundColor, value: UIColor.blue)

// Forground Color
let attributedString = "YOUR_STRING".getAttributedString(.foregroundColor, value: UIColor.red)

// Font
let attributedString = "YOUR_STRING".getAttributedString(.font, value: UIFont.boldSystemFont(ofSize: 15))

// Underline
let attributedString = "YOUR_STRING".getAttributedString(.underlineStyle, value: NSUnderlineStyle.single)

// Underline Color
let attributedString = "YOUR_STRING".getAttributedString(.underlineColor, value: UIColor.black)

    
// set attributed text on a UILabel
yourLabel.attributedText = attributedString

答案 3 :(得分:1)

请检查一下
var attrString = NSAttributedString(string: "labelText", attributes: [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont(name: "system", size: 12)])
label.attributedText = attrString

答案 4 :(得分:1)

首先,您需要将数据转换为字符串,然后使用此代码

let  attributes = [
   NSForegroundColorAttributeName: UIColor.black,
            ]
try NSAttributedString(string: "", attributes: attributes)

答案 5 :(得分:1)

对我来说唯一有效的方法是将HTML包装在<span>中,然后在其中应用样式:

let modifiedFontString = "<span style=\"font-family: Lato-Regular; font-size: 14; color: rgb(60, 60, 60)\">" + originalHTMLString + "</span>"

尝试此扩展程序:

extension String {

    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }

    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }

    func convertToAttributedString() -> NSAttributedString? {
        let modifiedFontString = "<span style=\"font-family: Lato-Regular; font-size: 14; color: rgb(60, 60, 60)\">" + self + "</span>"
        return modifiedFontString.htmlToAttributedString
    }
}

您可以这样使用它:

someLabel.attributedString = someHTMLString.convertToAttributedString()

希望有帮助!

答案 6 :(得分:0)

你可以这样设置

let attribute: [String : Any] = [NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize, weight: UIFontWeightThin),
    NSForegroundColorAttributeName: UIColor.red]

let attributedText = NSAttributedString(string: "Your String", attributes: attribute)