Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change title and message font of alert using UIAlertController in Swift

I am trying to change the title and message font for an alert shown using UIAlertController I am trying to do using an NSAttributedStirng, but it gives compiler error that a NSAttributed string cannot be taken instead of Stirng I tried something similar to this

var title_attrs = [NSFontAttributeName : CustomFonts.HELVETICA_NEUE_MEDIUM_16]
var msg_attrs = [NSFontAttributeName : CustomFonts.HELVETICA_NEUE_REGULAR_14]
var title = NSMutableAttributedString(string:"Done", attributes:title_attrs)

var msg = NSMutableAttributedString(string:"The job is done ", attributes:msg_attrs)
let alertController = UIAlertController(title: title, message: title , preferredStyle: UIAlertControllerStyle.Alert)

Can someone guide me how can I achieve this?

like image 690
Abhilasha Avatar asked Nov 06 '14 10:11

Abhilasha


3 Answers

Swift 3 Version:

extension UIAlertController {
    func changeFont(view: UIView, font:UIFont) {
        for item in view.subviews {
            if item.isKind(of: UICollectionView.self) {
                let col = item as! UICollectionView
                for  row in col.subviews{
                    changeFont(view: row, font: font)
                }
            }
            if item.isKind(of: UILabel.self) {
                let label = item as! UILabel
                label.font = font
            }else {
                changeFont(view: item, font: font)
            }

        }
    }

    open override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        let font = YOUR_FONT
        changeFont(view: self.view, font: font! )
    }
}
like image 66
Maysam Avatar answered Oct 19 '22 08:10

Maysam


I think Apple removed the attributedTitle and -message from the API. It was never part of the public API so it might be that Apple will not allow your app in the app store if you used it.

You should use the UIAlertController as is. If you want to customise it a bit see this NSHipster post. If you want more control, create a custom View to display.

like image 4
Tom Avatar answered Oct 19 '22 08:10

Tom


    let myString  = "Alert Title"
    var myMutableString = NSMutableAttributedString()
    myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:myString.characters.count))
    alertController.setValue(myMutableString, forKey: "attributedTitle")
    alertController.setValue(myMutableString, forKey: "attributedMessage")
like image 1
Hamed Avatar answered Oct 19 '22 07:10

Hamed