Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UIAlertController's title fontsize

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:

UIAlertViewController with large title

like image 443
Jacob Ahlberg Avatar asked Aug 30 '18 11:08

Jacob Ahlberg


1 Answers

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)

}

enter image description here

like image 77
Sunny Avatar answered Oct 27 '22 04:10

Sunny