I am using new UIAlertController for showing alerts. I have this code:
// nil titles break alert interface on iOS 8.0, so we\'ll be using empty strings
UIAle
Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there
import Foundation
import UIKit
extension UIAlertController {
//Set background color of UIAlertController
func setBackgroudColor(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 setTitle(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 title = self.message else {
return
}
let attributedString = NSMutableAttributedString(string: title)
if let titleFont = font {
attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
}
if let titleColor = color {
attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
}
self.setValue(attributedString, forKey: "attributedMessage")//4
}
//Set tint color of UIAlertController
func setTint(color: UIColor) {
self.view.tintColor = color
}
}
Now On any action Show Alert
func tapShowAlert(sender: UIButton) {
let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
// Change font and color of title
alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
// Change font and color of message
alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
// Change background color of UIAlertController
alertController.setBackgroudColor(color: UIColor.black)
let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(actnOk)
alertController.addAction(actnCancel)
self.present(alertController, animated: true, completion: nil)
}
Result