问题描述
我正在iOS 9中使用Swift.我想为UIAlertAction
自定义字体.我在这些问题中搜索了一个迅速的答案:
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:
是是否可以在带有iOS8的新XCode中自定义UIAlertController的字体和外观?
对于Objective-C的答案,这个问题是: UIAlertController自定义字体,大小,颜色
And this question for an Objective-C answer:UIAlertController custom font, size, color
但是对于自定义UIAlertAction
的字体,没有解决方案.
But there was no solution for customizing the font for a UIAlertAction
.
我相信问题是UIAlertAction
将NSString
用于其title
属性. 在Github上查看演示项目.
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")
但是据我所知,无法为NSString
设置自定义字体和大小.如果改用UILabel
,则自定义字体很容易.但是我似乎对字符串的局限性感到困惑.有谁知道一种分配自定义字体的方法?大小转换为字符串,还是我相信没有办法做到这一点?
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?
推荐答案
您将使用NSAttributedString
(或其可变的对等物NSMutableAttributedString
)来创建包含自定义信息的字符串.由于构造函数采用NSString
(在Swift中为String
),因此不会采用NSAttributedString
(NSAttributedString
不是NSString
的子类.).
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
.).
您可以使Swift编译器使用unsafeBitCast
传递NSAttributedString
,但是UIAlertAction
可能不喜欢它.
You could fudge the Swift compiler into passing an NSAttributedString
using unsafeBitCast
, but UIAlertAction
may not like it.
查看 UIAlertController自定义字体,大小,颜色,看来您可以使用KVO进行设置.这样做的代码是相似的:
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")
这篇关于是否可以设置自定义字体& NSString的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!