简体   繁体   中英

iOS 10 and setting custom font for attributed text

I've ported my app to XCode 8 and Swift 3 language syntax. Ever since doing so I've had lots of problems, setting a custom font being my current problem:

var sText = "Hello world, this is some text that I'm going to try to format ok?"
var attText = NSMutableAttributedString(string: sText)

var attrs = [NSFontAttributeName: UIFont(name: "Arial", size: 16)]
attText.addAttributes(attrs, range: NSMakeRange(0, sText.characters.count))

lblLabel1.attributedText = attText

So this code crashes every time with an "unrecognized selector sent to instance". Funny enough, setting other properties (like foreground color) work just fine... Just not fonts. I've tried custom fonts, system fonts, other named fonts... nothing seems to work. Anyone else run into this? Is there something I'm doing wrong here??? This code works fine in XCode 7 and even legacy Swift in XCode 8

Thanks in advance...

James

UIFont(name:) returns an Optional, so you have to unwrap it before use:

var sText = "Hello world, this is some text that I'm going to try to format ok?"
var attText = NSMutableAttributedString(string: sText)
if let arial = UIFont(name: "Arial", size: 16) {
    var attrs = [NSFontAttributeName: arial]
    attText.addAttributes(attrs, range: NSMakeRange(0, sText.characters.count))
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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