更改UIAlertController的标题字体大小

时间:2018-08-30 11:24:47

标签: swift swift4 nsmutableattributedstring uialertviewcontroller

我正在尝试在fontSize中更改标题UIAlertController,但是我无法管理如何将NSMutableAttributedString设置为title属性。 / p>

因此,我一直在使用以下代码创建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.
}

或者也许有一种更简单的方法来解决这个问题?


我的目标是拥有下图所示的图像:

UIAlertViewController with large title

2 个答案:

答案 0 :(得分:2)

您可以使用此代码制作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)

}

enter image description here

答案 1 :(得分:0)

除使用private API外,别无他法。

我建议您使用要自定义的属性来制作AlertViewController。