Is it possible to set custom font & size for NSStr

2020-04-01 08:07发布

问题:

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?

回答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")