2015-11-04 93 views
0

我正在iOS 9中使用Swift。我想自定义UIAlertAction的字体。我搜索这些问题对于斯威夫特的回答:是否可以为NSString设置自定义字体和大小?

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?

而这个问题对于一个Objective-C的答案: UIAlertController custom font, size, color

但有自定义的字体了无解UIAlertAction

我认为问题在于UIAlertActiontitle属性使用NSStringSee demo project on Github.

我想创建一个字符串,像这样:

let originalString: String = "OK" 
let myString: NSString = originalString as NSString 

,然后自定义字符串的字体大小&。

alertController!.actions[0].setValue(myString, forKey: "title") 

但据我所知,有没有办法将其设置为自定义的字体和大小:然后将我的行为给报警控制器后,使用键 - 值编码字符串分配给我的行动NSString。如果它使用了UILabel,那么定制字体会很容易。但我似乎被卡住了字符串的限制。有没有人知道一种方法来分配一个字符串的大小自定义字体,或者我相信有没有办法做到这一点正确?

回答

1

您可以使用NSAttributedString(或其可变对象NSMutableAttributedString)制作带有自定义信息的字符串。由于构造函数采用NSString(或Swift中的String),因此不会产生NSAttributedStringNSAttributedString不是NSString的子类)。

你可以把Swift编译器变成传递NSAttributedString使用unsafeBitCast,但UIAlertAction可能不喜欢它。


看着UIAlertController custom font, size, color,似乎你可以使用KVO来设置它。这样做的代码是类似的:

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

看起来你是对的不喜欢软糖。我试过这个:'let hogan = NSAttributedString(string:“Leg Drop”,attributes:[NSFontAttributeName:UIFont(name:“Avenir Next”,size:22)!])'unscafeHogan:NSString = unsafeBitCast(hogan,NSString自己)' 然后添加它:'alertController!.actions [0] .setValue(unsafeHogan,forKey:“title”)' 它编译好了,但抛出了一个运行时错误: _终止应用程序由于未捕获异常'NSInvalidArgumentException'原因:' - [NSConcreteAttributedString isEqualToString:]:无法识别的选择发送到实例0x7fa0e87accf0_ 猜你不能欺骗它! – peacetype

相关问题