我试图在fontSize
中更改标题UIAlertController
,但我无法管理如何将NSMutableAttributedString
设置为title
属性。
因此,我一直用以下代码创建NSMutableAttributedString
:
let title = NSMutableAttributedString(string: user.fullName)
let range = NSRange(location: 0, length: title.length)
title.addAttribute(NSAttributedStringKey.font, value: UIFont.TextStyle.largeTitle, range: range)
现在对我来说棘手的部分是如何弄清楚如何将新标题设置为UIAlertController
,因为它期望String?
值。
我环顾四周,发现在展示UILabel
时我应该在完成区内创建一个UIAlertController
。但是如何用我自己的自定义title
覆盖UIAlertController
中的UILabel
属性?
present(myUIAlertController, animated: true) {
// Creating the UILabel depending on string length
// Set the NSMutableAttributedString value to the custom UILabel and override title property.
}
或者甚至有更简单的方法来解决这个问题?
您可以使用此代码制作UIAlertController
的标题和消息。您可以根据需要进行自定义。您可以在图像中看到结果。我不确定你能把它放在Appstore上。
func showAlert() {
let alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
let titleAttributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 25)!, NSAttributedStringKey.foregroundColor: UIColor.black]
let titleString = NSAttributedString(string: "Name Last name", attributes: titleAttributes)
let messageAttributes = [NSAttributedStringKey.font: UIFont(name: "Helvetica", size: 17)!, NSAttributedStringKey.foregroundColor: UIColor.red]
let messageString = NSAttributedString(string: "Company name", attributes: messageAttributes)
alert.setValue(titleString, forKey: "attributedTitle")
alert.setValue(messageString, forKey: "attributedMessage")
let labelAction = UIAlertAction(title: "Label", style: .default, handler: nil)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(labelAction)
alert.addAction(deleteAction)
alert.addAction(cancelAction)
self.navigationController?.present(alert, animated: true, completion: nil)
}
除了使用private API之外别无他法。
我建议你使用你想要自定义的属性来制作AlertViewController。