首页 > 解决方案 > 更改 UIAlertController 的标题字体大小

问题描述

我正在尝试更改 中的标题fontSizeUIAlertController但我无法管理如何将我NSMutableAttributedString的设置为title-property。

因此,我一直在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-property ?UIAlertControllerUILabel

present(myUIAlertController, animated: true) {
    // Creating the UILabel depending on string length
    // Set the NSMutableAttributedString value to the custom UILabel and override title property.
}

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


我的目标是如下图所示:

带有大标题的 UIAlertViewController

标签: swiftswift4nsmutableattributedstringuialertviewcontroller

解决方案


您可以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)

}

在此处输入图像描述


推荐阅读