1

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

James Scott
  • 990
  • 2
  • 10
  • 29
  • 1
    what error message are you getting? – JAB Oct 12 '16 at 18:52
  • 1
    If it crashes, what's the error message? It is an out of bound issue? If YES, I think that's an issue about how String counts characters, so try a `NSMakeRange(0, (sText as NSString).length)` or something similar? Also, if you want to set the same effect for the whole text, why don't you use the `NSMutableAttributedString` init method where you can pass the `attrs`? – Larme Oct 12 '16 at 18:53
  • Hi all, to clarify: "unrecognized selector sent to instance" is the error I'm getting. – James Scott Oct 13 '16 at 10:56
  • Also, not sure why people are downvoting this question. I know how to code, and this is definitely some type of bug. Did anyone even try the code out in XCode 8 with a Swift 3 project? – James Scott Oct 13 '16 at 10:57
  • I tried with swift 3 project and Xcode 8, posted a very well working answer to which you replied with same comment of crash, thats why I uploaded a sample on dropbox and edited my answer with a dropbox link, with exactly the same code that I posted. – Rajan Maheshwari Oct 13 '16 at 13:25

1 Answers1

2

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))
    // ...
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253