Change UIAlertController's title fontsize

試著忘記壹切 提交于 2020-01-04 15:14:39

问题


I'm trying to change the title fontSize in an UIAlertController, but I can't manage how to set my NSMutableAttributedString to the title-property.

So for I've been creating the NSMutableAttributedString with the following code:

let title = NSMutableAttributedString(string: user.fullName)
let range = NSRange(location: 0, length: title.length)
title.addAttribute(NSAttributedStringKey.font, value: UIFont.TextStyle.largeTitle, range: range)

Now the tricky part for me is how to figure out how to set the new title to the UIAlertController, because it's expecting a String? value.

I looked around and found out that I should probably create a UILabel within the completion block when presenting the UIAlertController. But how do I override the title-property in the UIAlertController with my own custom UILabel?

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

Or maybe there's even an easier way to solve this?


My goal is to have like the image below:


回答1:


You can make title and message of UIAlertController attributed by using this code. You can customize as per your need. You can see the result in the image. I am not sure you can put it on 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)

}




回答2:


There is no way except using of private API.

I can suggest you to make your AlertViewController with properties that you want to customize.



来源:https://stackoverflow.com/questions/52095864/change-uialertcontrollers-title-fontsize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!