How to edit UIAlertAction text font size and color
Asked Answered
N

7

21

How to edit UIAlertAction text size and color? I have taken a UIAlertController acoording to it how to edit the size. This i smy Code

UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Do you wish to logout?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *logOut = [UIAlertAction actionWithTitle:@"Log Out" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];

Now i want my 'Log Out' text with font size 22 and green color and in semibold.

Narda answered 10/6, 2016 at 9:7 Comment(4)
You need to set the tintColor See my answer here: https://mcmap.net/q/582040/-how-to-change-tint-color-of-uialertcontrollerHardner
How can tintColor change the font size??Narda
[controller.view setTintColor:[UIColor yellowColor]]; to change tint color.Vegetative
Possible duplicate of Is it possible to edit UIAlertAction title font size and style?Lozenge
E
46

You can update text color using

       UIAlertAction *myGoalAction = [UIAlertAction
                                    actionWithTitle:NSLocalizedString(@"My Title", @"My Title")
                                    style:UIAlertActionStyleDefault
                                    handler:^(UIAlertAction *action)
                                    {

                                    }];
       [myGoalAction setValue:[UIColor greenColor] forKey:@"titleTextColor"];

There is no efficient way to update font size.I will suggest you to use standard font size.

UIAlertAction title label is private variable and not accessible directly. Label comes inside 3 level private view hierarchy. Showing logout action with bigger font make sense for app.

There are many open source solution available.I will recommend to try this

Encumbrancer answered 10/6, 2016 at 12:1 Comment(4)
My client's app requirement to show LogOut font with size 17 and weight semibold.Narda
UIAlertAction title label is private variable and not accessible directly. Label comes inside 3 level private view hierarchy. So updating it using hack way will give blunder to user (UI will not update randomly which will hard to fix later). Showing logout action with bigger font make sense for app. There are many open source solution available. I have mention one in my answer.Encumbrancer
I will suggest to go with this solution is it is category over UIAlertView controller. and have good rating in sort span of time.Encumbrancer
for swift3 users: let alertAction: UIAlertAction(title: "Acknowledge", style: .default, handler: nil) alertAction.setValue(UIColor.green, forKey: "titleTextColor") if you want to change the text color of the button in the alert controllerPetrina
O
5

Here is a solution for changing the text color in Swift:

let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
action.setValue(UIColor.black, forKey: "titleTextColor")

Or you could use this extension:

extension UIAlertAction {
    var titleTextColor: UIColor? {
        get { return self.value(forKey: "titleTextColor") as? UIColor } 
        set { self.setValue(newValue, forKey: "titleTextColor") }
    }
}
Overbear answered 24/1, 2020 at 16:13 Comment(0)
G
5

I've written an extension

extension UIAlertController{
    open override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        for i in self.actions {
            let attributedText = NSAttributedString(string: i.title ?? "", attributes: [NSAttributedString.Key.font : UIFont(name: "SFProText-Semibold", size: 20.0)!])

            guard let label = (i.value(forKey: "__representer") as AnyObject).value(forKey: "label") as? UILabel else { return }
            label.attributedText = attributedText
        }

    }
}
Goldeye answered 18/3, 2020 at 4:23 Comment(1)
good job Farhad. simple, useful and amazing.Gauffer
H
1

Changing the color is pretty simple.

You could just change the tintColor of the underlying view, however, due to a known bug introduced in iOS 9 (https://openradar.appspot.com/22209332), the tintColor is overridden by the application window's tintColor.

See my full answer to: How to change tint color of UIAlertController


You shouldn't change the UIAlertController font. However it still can be done, see this answer

Hardner answered 10/6, 2016 at 9:13 Comment(1)
what about font size??Narda
H
0

Use NSMutableAttributedString set the font size and color, use this below code,

UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Do you wish to logout?" message:@"" preferredStyle:UIAlertControllerStyleAlert];

NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Do you wish to logout?"];

[hogan addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:50.0] range:NSMakeRange(24, 11)];

[hogan addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,35)];

[controller setValue:hogan forKey:@"attributedTitle"];

UIAlertAction *logOut = [UIAlertAction actionWithTitle:@"Log Out" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}];

hope its helpful

Heyduck answered 10/6, 2016 at 9:20 Comment(1)
question is to update UIAlertAction font size and color .Encumbrancer
C
0

Try this:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Do you wish to logout?" message:@"abcd" preferredStyle:UIAlertControllerStyleActionSheet];

NSMutableAttributedString *xyz = [[NSMutableAttributedString alloc] initWithString:@"pqrs"];

[xyz addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:30.0]
              range:NSMakeRange(20, 15)];
[alert setValue:xyz forKey:@"attributedTitle"];



UIAlertAction *logout = [UIAlertAction actionWithTitle:@"logout" 
                                        style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction *action){
                                                    //your code for handling this
}];
UIImage *Image = [UIImage imageNamed:@"yourImage"];
[logout setValue:accessoryImage forKey:@"image"];
Cabretta answered 10/6, 2016 at 9:25 Comment(1)
@LianvanderVyver it will crash your app if the image is probably too large. I fixed this by scaling the Image's size before setting it to the key "image"Caston
H
-1

Here is giving my answer Swift 5. We can apply custom fonts to AlertView and AlertAddAction.
1st Create AlertView Extention. Inside Extension

import Foundation
import UIKit

extension UIAlertController {
    
    func applyBranding() {
        
        applyAlertTitleBranding()
        applyAlertMessageBranding()
    }
    
    func applyAlertTitleBranding() {
        let titleFont = [kCTFontAttributeName: UIFont(name: "Montserrat-Medium", size: 18.0)!]
        let titleAttrString = NSMutableAttributedString(string: title!, attributes: titleFont as [NSAttributedString.Key : Any])
        let titleColor = UIColor(red: 34.0/255/0, green: 34.0/255/0, blue: 34.0/255/0, alpha: 1.0)
        titleAttrString.addAttribute(NSAttributedString.Key.foregroundColor,
                                     value: titleColor,
                                     range: NSRange(location: 0, length: title!.count))
        setValue(titleAttrString, forKey: "attributedTitle")
    }
    
    func applyAlertMessageBranding() {
        let messageFont = [kCTFontAttributeName: UIFont(name: "Montserrat-Regular", size: 14.0)!]
        let messageAttrString = NSMutableAttributedString(string: message!, attributes: messageFont as [NSAttributedString.Key : Any])
        let messageTitleColor = UIColor(red: 68.0/255/0, green: 68.0/255/0, blue: 68.0/255/0, alpha: 1.0)
        messageAttrString.addAttribute(NSAttributedString.Key.foregroundColor,
                                       value: messageTitleColor,
                                       range: NSRange(location: 0, length: message!.count))
        setValue(messageAttrString, forKey: "attributedMessage")
    }
    
    func applyNoActionBranding() {
        let font = [kCTFontAttributeName: UIFont(name: "Montserrat-Medium", size: 16.0)!]
        for actionButton in actions {
            let titleAttrString = NSMutableAttributedString(string: actionButton.title!, attributes: font as [NSAttributedString.Key : Any])
            actionButton.setValue(titleAttrString, forKey: "attributedTitleForAction")
        }
    }
    
    func applyYesActionBranding() {
        let font = [kCTFontAttributeName: UIFont(name: "Montserrat-Regular", size: 16.0)!]
        for actionButton in actions {
            let titleAttrString = NSMutableAttributedString(string: actionButton.title!, attributes: font as [NSAttributedString.Key : Any])
            actionButton.setValue(titleAttrString, forKey: "attributedTitleForAction")
        }
    }
}



 

2nd call those AlertView functions where ever you need. For example call in ViewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()

    showAlert()
}

func showAlert() {

    let alertVc = UIAlertController(title: "Some Title", message: "Some message", preferredStyle: .alert)
    
    //No action
    let noAction = UIAlertAction(title: "No", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        alertVc.dismiss(animated: true, completion: nil)
    })
    
    //Yes action
    let yesAction = UIAlertAction(title: "Yes", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        self.deleteFunction(address)
        alertVc.dismiss(animated: true, completion: nil)
    })
    
    alertVc.applyBranding()
    alertVc.applyNoActionBranding()
    alertVc.applyYesActionBranding()
    alertVc.addAction(noAction)
    alertVc.addAction(yesAction)
    
    alertVc.view.tintColor = .blue
    DispatchQueue.main.async(execute: {
        self.present(alertVc, animated: true, completion: nil)
    })
}

Hope It's work for all 🙂

Hire answered 14/9, 2020 at 18:1 Comment(4)
UIAlertAction is not key value coding-compliant for the key attributedTitleForActionDupion
@Dupion What does mean. I didn’t get u. Please explain me more.Hire
@SreekanthG You know, you are calling applyNoActionBranding before adding any action. That's why you didn't get any error. It should get an error of no key value coding-compliant for the key attributedTitleForActionLovettalovich
Yes, I got error as well, This answer doesn't work for me as wellSplashdown

© 2022 - 2024 — McMap. All rights reserved.