是否可以为NSString设置自定义字体和大小?

问题描述 投票:0回答:1

我在iOS 9中使用Swift。我想为UIAlertAction自定义字体。我搜索了这些问题以获得Swift答案:

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的字体。

我认为问题在于UIAlertAction使用NSString作为其title财产。 See demo project on Github.

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

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

然后自定义字符串的字体和大小。然后在将我的操作添加到警报控制器后,使用键值编码将字符串分配给我的操作:

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

但据我所知,没有办法为NSString设置自定义字体和大小。如果它使用UILabel代替,那么很容易定制字体。但我似乎陷入了字符串的限制。有没有人知道为字符串分配自定义字体和大小的方法,或者我相信没有办法做到这一点?

string swift nsstring ios9 uialertaction
1个回答
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")
© www.soinside.com 2019 - 2024. All rights reserved.