I'm working with Swift in iOS 9. I want to customize the font for a UIAlertAction
. I searched these questions for a Swift answer:
Change the Font of UIAlertAction in Swift
Is it possible to customize the font and appearance of a UIAlertController in the new XCode w/ iOS8?
And this question for an Objective-C answer: UIAlertController custom font, size, color
But there was no solution for customizing the font for a UIAlertAction
.
I believe the problem is that a UIAlertAction
uses an NSString
for its title
property. See demo project on Github.
I would like to create a string like so:
let originalString: String = "OK"
let myString: NSString = originalString as NSString
And then customize the string's font & size. Then after adding my actions to the alert controller, assign the string to my actions using key-value coding:
alertController!.actions[0].setValue(myString, forKey: "title")
But as far as I can tell, there is no way to set a custom font and size for an NSString
. If it used a UILabel
instead, then it would be easy to customize the font. But I seem to be stuck with the limitations of strings. Does anyone know a way to assign a custom font & size to a string, or am I correct in believing there is no way to do this?
let hogan = NSAttributedString(string: "Leg Drop", attributes: [NSFontAttributeName: UIFont(name: "Avenir Next", size: 22)!])
let unsafeHogan : NSString = unsafeBitCast(hogan, NSString.self)
Then added it:alertController!.actions[0].setValue(unsafeHogan, forKey: "title")
It compiled OK but threw a runtime error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteAttributedString isEqualToString:]: unrecognized selector sent to instance 0x7fa0e87accf0 Guess you can't fool it! – Grosgrain