Is it possible to set custom font & size for NSString?
Asked Answered
G

1

0

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?

Grosgrain answered 4/11, 2015 at 22:4 Comment(0)
U
1

You would use NSAttributedString (or its mutable counterpart, NSMutableAttributedString) to make a string with custom info. As the constructor takes an NSString (or String in Swift), it will not take an NSAttributedString (NSAttributedString isn't a subclass of NSString.).

You could fudge the Swift compiler into passing an NSAttributedString using unsafeBitCast, but UIAlertAction may not like it.


Looking at UIAlertController custom font, size, color, it seems that you can set it using KVO. The code for doing of so is similar:

var alertVC = UIAlertController(title: "Dont care what goes here, since we're about to change below", message: "", preferredStyle: .ActionSheet)
let hogan = NSMutableAttributedString(string: "Presenting the great... Hulk Hogan!")
hogan.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(50), range: NSMakeRange(24, 11))

alertVC.setValue(hogan, forKey: "attributedTitle")
Uranium answered 4/11, 2015 at 22:57 Comment(1)
Looks like you were right about not liking the fudge. I tried 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

© 2022 - 2024 — McMap. All rights reserved.