Change font, text color and background color of UIAlertController

UIAlertController is derived from UIViewController inside the UIKit framework. It is used to show the alert messages.
Changing color, font, and the background color is not the built-in property of UIAlertController so here we are going to do some trick to achieve these features. We will do this using UIAlertController extension so the code will be reusable throughout the projects.
Now let’s start coding…

Creating a new project

– Open XCode, got to File -> New -> Project.. And choose Single View App
– Name it AlertController or whatever you want

Adding UIAlertController Extension

– Create a new swift file and name it UIAlertController+Customization

-Add below code in this file
import Foundation
import UIKit

extension UIAlertController {
    
    //Set background color of UIAlertController
    func setBackgroundColor(color: UIColor) {
        if let bgView = self.view.subviews.first, let groupView = bgView.subviews.first, let contentView = groupView.subviews.first {
            contentView.backgroundColor = color
        }
    }
    
    //Set title font and title color
    func setTitlet(font: UIFont?, color: UIColor?) {
        guard let title = self.title else { return }
        let attributeString = NSMutableAttributedString(string: title)//1
        if let titleFont = font {
            attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
                                          range: NSMakeRange(0, title.utf8.count))
        }
        
        if let titleColor = color {
            attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
                                          range: NSMakeRange(0, title.utf8.count))
        }
        self.setValue(attributeString, forKey: "attributedTitle")//4
    }
    
    //Set message font and message color
    func setMessage(font: UIFont?, color: UIColor?) {
        guard let message = self.message else { return }
        let attributeString = NSMutableAttributedString(string: message)
        if let messageFont = font {
            attributeString.addAttributes([NSAttributedString.Key.font : messageFont],
                                          range: NSMakeRange(0, message.utf8.count))
        }
        
        if let messageColorColor = color {
            attributeString.addAttributes([NSAttributedString.Key.foregroundColor : messageColorColor],
                                          range: NSMakeRange(0, message.utf8.count))
        }
        self.setValue(attributeString, forKey: "attributedMessage")
    }
    
    //Set tint color of UIAlertController
    func setTint(color: UIColor) {
        self.view.tintColor = color
    }
}

Set background color

Use below function to change background color
func setBackgroundColor(color: UIColor)

Set title font and color

//Set title font and title color
func setTitlet(font: UIFont?, color: UIColor?)
Pass your font and color in this function and it will change your font and color. You can pass nil if you don’t wish the change color of font.
1. Get NSMutableAttributedString object from title text.
2. Add font attribute in attributeString
3. Add color attribute in attributeString
4. Set this attributeString to key attributedTitle

Set message font and color

//Set message font and message color
func setMessage(font: UIFont?, color: UIColor?)
Use this above function to change color and font of UIAlertController message. Both parameters are optional so you can pass nil if don’t wish to change any.

Move to ViewController class and show Alert

Now move to your ViewController add below code in your viewDidAppear function.
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let alertController = UIAlertController(title: "Alert!!", message: "This is alert message", preferredStyle: .alert)
        
        // Change font and color of title
        alertController.setTitlet(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.white)
        
        // Change font and color of message
        alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
        
        // Change background color of UIAlertController
        alertController.setBackgroundColor(color: UIColor.black)
        
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(action)
        self.present(alertController, animated: true, completion: nil)
    }
}

Now run the code.

Read our next article: Upload image, video and files to S3 bucket using one line of code

6 comments on “Change font, text color and background color of UIAlertController

  1. Victor Kosse

    Thanks! Great info but at least in sift 5 you should change ‘title.utf8.count’ to ‘title.count’ and ‘message.utf8.count’ to ‘message.count’

    Reply
  2. pradeesh

    its working fine but MESSAGE content size not working only take small message like “hello world hello ” …its not working more ten words

    Reply
  3. g

    Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your blog?
    My blog is in the very same area of interest as
    yours and my visitors would really benefit from some of the information you provide here.
    Please let me know if this okay with you.
    Thanks!

    Reply
  4. CLAUDIO JOSE DA SILVA ME

    Great article. My question is to have each UIAlertAction button with different backgroundColor. Is it possible ? thanks

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *