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

5
  • 1
    what error message are you getting? Commented Oct 12, 2016 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? Commented Oct 12, 2016 at 18:53
  • Hi all, to clarify: "unrecognized selector sent to instance" is the error I'm getting. Commented Oct 13, 2016 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? Commented Oct 13, 2016 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. Commented Oct 13, 2016 at 13:25

1 Answer 1

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))
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

you are absolutely right buddy! That was it. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.