如何在UIAlertcontroller中将属性化文本设置为消息。我的代码如下所示,但它会使应用程序崩溃。
// create Attributed text
let myAttribute = [NSForegroundColorAttributeName: UIColor(red:122.0/255, green:125.0/255, blue:131.0/255, alpha:1.0),NSFontAttributeName: Constant.flinntRegularFont(15)]
let myAttribute2 = [NSForegroundColorAttributeName: UIColor.blackColor(),NSFontAttributeName: Constant.flinntMediumFont(15)]
let myString = NSMutableAttributedString(string: "You have been unsubscribed from ", attributes: myAttribute)
let myString2 = NSMutableAttributedString(string: self.course.course_name, attributes: myAttribute2)
let myString3 = NSMutableAttributedString(string: "\n\nYour refund will be initiated within one week.", attributes: myAttribute)
let myString4 = NSMutableAttributedString(string: "\n\nFor any help call us on", attributes: myAttribute)
let myString5 = NSMutableAttributedString(string: " 079-4014 9800", attributes: myAttribute2)
let myString6 = NSMutableAttributedString(string: " between 9:30 am to 6:30 pm on Monday to Saturday.\n\nWe will be always here with great deals to share.", attributes: myAttribute)
myString.appendAttributedString(myString2)
myString.appendAttributedString(myString3)
myString.appendAttributedString(myString4)
myString.appendAttributedString(myString5)
myString.appendAttributedString(myString6)
当前UIAlertcontroller代码
let alert = UIAlertController(title: "", message: "Select course", preferredStyle: UIAlertControllerStyle.Alert)
alert.setValue(myAttribute, forKey: "attributedMessage") // this line make a crash.
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { (action) in
self.delegate?.courseRefundViewControllerCoursrRefunded?(self)
self.navigationController?.popViewControllerAnimated(true)
}))
self.presentViewController(alert, animated: true, completion: nil)
- 谢谢-谢谢
3条答案
按热度按时间kuarbcqp1#
由于DataType不匹配,您的应用程序正在崩溃。
alert.setValue(<value>, forKey: "attributedMessage")
这里的
<value>
必须是NSMutableAttributedString
的一个示例。但是您传递的是myAttribute,即
Dictionary
。它正在尝试调用
length
方法,但在Dictionary
上找不到,这就是应用程序崩溃的原因。试试看:
wf82jlnq2#
作为私有API的替代,您可以使用https://github.com/AntonPoltoratskyi/NativeUI
pod 'NativeUI/Alert', '~> 1.0'
它是一个从头开始实现的自定义视图控制器,看起来与本机
UIAlertController
完全相同。您可以传递
String
、NSAttributedString
或自定义内容视图。798qvoo83#
这里的答案在iOS 15中是可以接受的,但是如果苹果改变了他们的私有api,它会毫无预警地崩溃。讽刺的是,历史上,当他们公开这种api时,它会改变和破坏这样的东西。下面是一个安全使用私有api的方法: