swift - 更改 UIAlertController 的标题字体大小

标签 swift swift4 nsmutableattributedstring uialertviewcontroller

我正在尝试更改 UIAlertController 中的标题 fontSize,但我无法管理如何将我的 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? 值。

我环顾四周,发现在呈现 UIAlertController 时,我可能应该在完成 block 中创建一个 UILabel。但是,如何使用我自己的自定义 UILabel 覆盖 UIAlertController 中的 title 属性?

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

最佳答案

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

关于swift - 更改 UIAlertController 的标题字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095864/

相关文章:

ios - 将 UIViewcontroller 加载到比屏幕小的 s​​crollView 中?

ios - 单击按钮快速推送 UIViewController 两次

Swift 4 可解码 : How to map multiple values to a single enum value?

swift - Oauth2 URL 回调 Mac Swift 4

ios - 动画更改 NSMutableAttributedString 的一部分

ios - 每周切换一个存储的标志

ios - 调用重复定时器中的方法

ios11 - Xcode 9 重建问题?

iOS Swift - 将属性应用于 TextView 而不替换整个文本

objective-c - 将属性字符串中的正则表达式匹配替换为 Objective-C 中的图像