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

走远了吗. 提交于 2019-12-19 11:56:25

问题


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


来源:https://stackoverflow.com/questions/33532941/is-it-possible-to-set-custom-font-size-for-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!