UIAlertController แบบอักษรขนาดสีที่กำหนดเอง


118

ฉันใช้ UIAlertController ใหม่เพื่อแสดงการแจ้งเตือน ฉันมีรหัสนี้:

// nil titles break alert interface on iOS 8.0, so we'll be using empty strings
UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title message: message preferredStyle: UIAlertControllerStyleAlert];


UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle style: UIAlertActionStyleCancel handler: nil];

[alert addAction: defaultAction];

UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
[rootViewController presentViewController:alert animated:YES completion:nil];

ตอนนี้ฉันต้องการเปลี่ยนแบบอักษรชื่อและข้อความสีขนาดและอื่น ๆ วิธีใดดีที่สุดในการทำเช่นนี้

แก้ไข: ฉันควรใส่รหัสทั้งหมด ฉันสร้างหมวดหมู่สำหรับ UIView ที่สามารถแสดงการแจ้งเตือนที่ถูกต้องสำหรับเวอร์ชัน iOS

@implementation UIView (AlertCompatibility)

+( void )showSimpleAlertWithTitle:( NSString * )title
                          message:( NSString * )message
                cancelButtonTitle:( NSString * )cancelButtonTitle
{
    float iOSVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (iOSVersion < 8.0f)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                        message: message
                                                       delegate: nil
                                              cancelButtonTitle: cancelButtonTitle
                                              otherButtonTitles: nil];
        [alert show];
    }
    else
    {
        // nil titles break alert interface on iOS 8.0, so we'll be using empty strings
        UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title
                                                                       message: message
                                                                preferredStyle: UIAlertControllerStyleAlert];


        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle
                                                                style: UIAlertActionStyleCancel
                                                              handler: nil];

        [alert addAction: defaultAction];

        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootViewController presentViewController:alert animated:YES completion:nil];
    }
}

2
DISCLAIMER:สำหรับทุกคนที่อ่านคำตอบด้านล่าง Apple จะปฏิเสธแอปของคุณ หากคุณมักจะใช้ API ส่วนตัวใด ๆ และในคำตอบด้านล่างว่าเกิดอะไรขึ้น ..
Yash Bedi

คำตอบ:


98

ไม่แน่ใจว่าสิ่งนี้ขัดต่อ API / คุณสมบัติส่วนตัวหรือไม่ แต่การใช้ KVC ใช้ได้กับฉันบน ios8

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Dont care what goes here, since we're about to change below" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:50.0]
              range:NSMakeRange(24, 11)];
[alertVC setValue:hogan forKey:@"attributedTitle"];



UIAlertAction *button = [UIAlertAction actionWithTitle:@"Label text" 
                                        style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction *action){
                                                    //add code to make something happen once tapped
}];
UIImage *accessoryImage = [UIImage imageNamed:@"someImage"];
[button setValue:accessoryImage forKey:@"image"];

สำหรับบันทึกคุณสามารถเปลี่ยนแบบอักษรของการดำเนินการแจ้งเตือนได้เช่นกันโดยใช้ API ส่วนตัวเหล่านั้น อีกครั้งอาจทำให้แอปของคุณถูกปฏิเสธฉันยังไม่ได้พยายามส่งรหัสดังกล่าว

let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)

let action = UIAlertAction(title: "Some title", style: .Default, handler: nil)
let attributedText = NSMutableAttributedString(string: "Some title")

let range = NSRange(location: 0, length: attributedText.length)
attributedText.addAttribute(NSKernAttributeName, value: 1.5, range: range)
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "ProximaNova-Semibold", size: 20.0)!, range: range)

alert.addAction(action)

presentViewController(alert, animated: true, completion: nil)

// this has to be set after presenting the alert, otherwise the internal property __representer is nil
guard let label = action.valueForKey("__representer")?.valueForKey("label") as? UILabel else { return }
label.attributedText = attributedText

สำหรับ Swift 4.2 ใน XCode 10 ขึ้นไป 2 บรรทัดสุดท้ายคือ:

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

6
มันใช้งานได้ attributedTitleสำหรับชื่อและattributedMessageสำหรับข้อความ ไม่แน่ใจว่าเป็นทางออกที่ดีที่สุดหรือไม่ แต่ตอนนี้มันดีพอสำหรับฉัน
Libor Zapletal

2
การปรับแต่งทั้งหมดที่เราสามารถเพิ่มได้ในปุ่ม UIAlertController คืออะไร ??
Aanchal Chaurasia

1
ขอบคุณ! ฉันมีคำถามเล็ก ๆ - หนึ่งสามารถใช้แบบอักษรและสีที่กำหนดเองกับไทล์แอตทริบิวต์และข้อความในUIAlertController. จะทำเช่นเดียวกันได้UIAlertActionอย่างไร?
p0lAris

72
ฉันหวังว่าไม่มีใครวางแผนที่จะปล่อยสิ่งนี้ไปยัง App Store เนื่องจากใช้ API ส่วนตัว อย่างจริงจังฉันไม่รู้ว่าทำไมคำตอบเหล่านี้ถึงได้รับการยอมรับใน Stackoverflow เมื่อพวกเขาไม่ใช่ 'คำตอบ' จริงๆ สิ่งเหล่านี้คือการแฮ็กที่คุณอาจหรือไม่อาจหลีกเลี่ยงจากการเผยแพร่ในร้านแอปพลิเคชัน
TheCodingArt

3
สำหรับกรณีการเปิดตัวแอพในร้านแอพนั้น Apple อนุญาตให้ใช้ API ส่วนตัวบางส่วนได้ แต่ไม่ควรใช้ apis ซึ่งอาจเป็นอันตรายหรือส่งผลกระทบต่อระบบ / ความเป็นส่วนตัวของผู้ใช้ ดังนั้นอาจเป็นไปได้ว่าคำตอบนี้อาจเป็นที่ยอมรับของหลาย ๆ คนเนื่องจากสิ่งนี้เท่านั้น และอาจไม่ส่งผลกระทบต่อแอพสโตร์ ผู้ที่เคยใช้สิ่งนี้สามารถยืนยันได้หรือไม่ว่าแอปของตนไม่ถูกปฏิเสธ
Mehul Thakkar

67

คุณสามารถเปลี่ยนสีปุ่มได้โดยใช้สีอ่อนกับ UIAlertController

ใน iOS 9 หากตั้งค่าสีของหน้าต่างเป็นสีที่กำหนดเองคุณจะต้องใช้สีอ่อนทันทีหลังจากนำเสนอการแจ้งเตือน มิฉะนั้นสีอ่อนจะถูกรีเซ็ตเป็นสีของหน้าต่างที่คุณกำหนดเอง

// In your AppDelegate for example:
window?.tintColor = UIColor.redColor()

// Elsewhere in the App:
let alertVC = UIAlertController(title: "Title", message: "message", preferredStyle: .Alert)
alertVC.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alertVC.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))

// Works on iOS 8, but not on iOS 9
// On iOS 9 the button color will be red
alertVC.view.tintColor = UIColor.greenColor()

self.presentViewController(alert, animated: true, completion: nil)

// Necessary to apply tint on iOS 9
alertVC.view.tintColor = UIColor.greenColor()

20
เพื่อความชัดเจนการตั้งค่า tintColor หลังจากนำเสนอคอนโทรลเลอร์ทำงานได้ทั้งบน iOS 8 และ 9 ดังนั้นจึงไม่จำเป็นต้องตั้งค่าซ้ำสองครั้ง
arlomedia

ขอบคุณที่เพิ่มคำตอบ Swift และวิธีแก้ปัญหาสำหรับปัญหานี้ใน iOS 9
peacetype

3
เมื่อฉันแตะและลากนิ้วลงมันจะกลับไปเป็นสีเริ่มต้นอีกครั้ง ความคิดใด ๆ ?
msmq

นี่เป็นคำตอบเดียวที่ดีที่นี่
TheCodingArt

47

คุณสามารถเปลี่ยนสีของข้อความปุ่มโดยใช้รหัสนี้:

alertC.view.tintColor = your color;

บางทีนี่อาจจะช่วยคุณได้


@esilver คุณหาโซลูชันที่ใช้ได้กับ iOS9 หรือไม่?
เถ้า

1
ฉันไม่ได้. ฉันสร้างรายงานข้อบกพร่องด้วย Apple # 22391695
esilver

1
ข้อมูลเพิ่มเติมเกี่ยวกับเรื่องนี้ ดูเหมือนว่าเมื่อคุณเลื่อนรายการยาว ๆ รายการที่คุณแตะเพื่อเลื่อนจะกลายเป็นสีน้ำเงิน ...
เบจิล

3
ไม่มีงานนี้บน UIAlertController ใน iOS9 และ 9.1 .. ไม่ทราบว่าพวกของ Apple เป็นอย่างไร ... ต้องเปลี่ยนสีหน้าต่างด้วยตนเองทุกครั้งที่มีการเรียกตัวควบคุมการแจ้งเตือนและเปลี่ยนกลับในตัวจัดการ
Akhilesh Sharma

ใช้งานได้กับ iOS 9.3 เว้นแต่คุณจะแตะออกไปข้างนอก: กลับมาเป็นสีน้ำเงินของระบบ
Rémi Belzanti

35

ใน Xcode 8 Swift 3.0

@IBAction func touchUpInside(_ sender: UIButton) {

    let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)

    //to change font of title and message.
    let titleFont = [NSFontAttributeName: UIFont(name: "ArialHebrew-Bold", size: 18.0)!]
    let messageFont = [NSFontAttributeName: UIFont(name: "Avenir-Roman", size: 12.0)!]

    let titleAttrString = NSMutableAttributedString(string: "Title Here", attributes: titleFont)
    let messageAttrString = NSMutableAttributedString(string: "Message Here", attributes: messageFont)

    alertController.setValue(titleAttrString, forKey: "attributedTitle")
    alertController.setValue(messageAttrString, forKey: "attributedMessage")

    let action1 = UIAlertAction(title: "Action 1", style: .default) { (action) in
        print("\(action.title)")
    }

    let action2 = UIAlertAction(title: "Action 2", style: .default) { (action) in
        print("\(action.title)")
    }

    let action3 = UIAlertAction(title: "Action 3", style: .default) { (action) in
        print("\(action.title)")
    }

    let okAction = UIAlertAction(title: "Ok", style: .default) { (action) in
        print("\(action.title)")
    }

    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    alertController.addAction(okAction)

    alertController.view.tintColor = UIColor.blue
    alertController.view.backgroundColor = UIColor.black
    alertController.view.layer.cornerRadius = 40

    present(alertController, animated: true, completion: nil)

}

เอาท์พุต

แบบอักษรขนาดและสีที่กำหนดเอง UIAlertController


ขอโทษครับนี่คือการเริ่มต้น หากจำเป็นในคุณสมบัติฉันจะแจ้งให้คุณทราบ ...
iOS

24

การแปลคำตอบของ @ dupuis2387 อย่างรวดเร็ว คำนวณไวยากรณ์เพื่อกำหนดUIAlertControllerสีและแบบอักษรของหัวเรื่องผ่าน KVC โดยใช้attributedTitleคีย์

let message = "Some message goes here."
let alertController = UIAlertController(
    title: "", // This gets overridden below.
    message: message,
    preferredStyle: .Alert
)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ -> Void in
}
alertController.addAction(okAction)

let fontAwesomeHeart = "\u{f004}"
let fontAwesomeFont = UIFont(name: "FontAwesome", size: 17)!
let customTitle:NSString = "I \(fontAwesomeHeart) Swift" // Use NSString, which lets you call rangeOfString()
let systemBoldAttributes:[String : AnyObject] = [ 
    // setting the attributed title wipes out the default bold font,
    // so we need to reconstruct it.
    NSFontAttributeName : UIFont.boldSystemFontOfSize(17)
]
let attributedString = NSMutableAttributedString(string: customTitle as String, attributes:systemBoldAttributes)
let fontAwesomeAttributes = [
    NSFontAttributeName: fontAwesomeFont,
    NSForegroundColorAttributeName : UIColor.redColor()
]
let matchRange = customTitle.rangeOfString(fontAwesomeHeart)
attributedString.addAttributes(fontAwesomeAttributes, range: matchRange)
alertController.setValue(attributedString, forKey: "attributedTitle")

self.presentViewController(alertController, animated: true, completion: nil)

ใส่คำอธิบายภาพที่นี่


3
แล้วปุ่ม "ตกลง" ล่ะ? เราปรับแต่งได้ไหม
Hassan Taleb

@HassanTaleb ฉันไม่พบวิธีที่ยอดเยี่ยมในการปรับแต่งปุ่ม คุณสามารถตั้งค่าtintColorบนviewหรือผ่านทางappearanceWhenContainedInแต่สีออกไปทันทีที่คุณสัมผัสมัน ยังคงค้นหาคำตอบแม้ว่า
Robert Chen

@AbdulMomen عبدالمؤمنคุณเห็นข้อความแสดงข้อผิดพลาดอะไร ข้อมูลโค้ดถือว่า FontAwesome ได้รับการตั้งค่าแล้ว
Robert Chen

1
@RobertChen เพื่อแก้ปัญหาเพียงแค่ใส่สีหลัง: self.presentViewController(alertController, animated: true, completion: nil)เราสามารถเปลี่ยนแบบอักษรของปุ่ม "ตกลง" ได้หรือไม่?
Hassan Taleb

4
นี่ไม่ถือเป็น API ส่วนตัวใช่ไหม
Jinghan Wang

13

ใช้UIAppearanceโปรโตคอล ตัวอย่างการตั้งค่าแบบอักษร - สร้างหมวดหมู่เพื่อขยาย UILabel:

@interface UILabel (FontAppearance)
@property (nonatomic, copy) UIFont * appearanceFont UI_APPEARANCE_SELECTOR;
@end


@implementation UILabel (FontAppearance)

-(void)setAppearanceFont:(UIFont *)font {
    if (font)
        [self setFont:font];
}

-(UIFont *)appearanceFont {
    return self.font;
}

@end

และการใช้งาน:

UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil];
[appearanceLabel setAppearanceFont:[UIFont boldSystemFontOfSize:10]]; //for example

ผ่านการทดสอบและใช้งานได้อย่างมีสไตล์UIAlertControllerStyleActionSheetแต่ฉันคิดว่ามันก็ใช้ได้UIAlertControllerStyleAlertเช่นกัน

ปล. ตรวจสอบความพร้อมใช้งานของคลาสแทน iOS เวอร์ชันดีกว่า

if ([UIAlertController class]) {
    // UIAlertController code (iOS 8)
} else {
    // UIAlertView code (pre iOS 8)
}

มันใช้งานได้ แต่วิธีนี้ฉันไม่สามารถมีขนาดที่แตกต่างกันสำหรับข้อความและสำหรับชื่อ
Libor Zapletal

วิธีนี้ใช้งานได้ แต่เมื่อคลิกการกระทำฟอนต์จะเปลี่ยนกลับไปเป็นขนาดเดิม? สิ่งนี้เกิดขึ้นกับคุณหรือไม่?
Larry

ฉันมีปัญหาเดียวกันกับ @Larry และฉันยังไม่พบวิธีจัดการกับมัน .. มีไหม?
alasker

13

สวิฟท์ 5 และ 5.1 สร้างไฟล์แยกต่างหากและใส่รหัส UIAlertController Customization

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
  }
}

ตอนนี้ในการดำเนินการใด ๆ แสดงการแจ้งเตือน

  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)
  }

ผลลัพธ์

ใส่คำอธิบายภาพที่นี่


1
เรากำลังเข้าถึง Api ส่วนตัวตรงนี้หรือไม่ คุณได้เปิดตัวแอพที่มีคุณสมบัติการแจ้งเตือนที่กำหนดเองเหล่านี้หรือไม่?
Yash Bedi

@YashBedi ใช้ API ส่วนตัวและ Apple อาจปฏิเสธแอปของคุณสำหรับการใช้งาน "API ที่ไม่ใช่สาธารณะ" ไม่ฉันยังไม่ได้เปิดตัวแอปใด ๆ
Gurjinder Singh

สิ่งนี้กล่าวถึงในไซต์นักพัฒนาของ Apple -> สำคัญคลาส UIAlertController มีไว้เพื่อใช้ตามสภาพและไม่รองรับคลาสย่อย ลำดับชั้นของมุมมองสำหรับคลาสนี้เป็นแบบส่วนตัวและต้องไม่มีการแก้ไข
Gurjinder Singh

เข้าใจแล้วบอสขอบคุณ
Yash Bedi

@Darkglow โปรดระบุข้อผิดพลาด ฉันสามารถสร้างรหัสเดียวกันได้สำเร็จด้วย Swift 5.1
Gurjinder Singh

12

ใช้UIAppearanceโปรโตคอล ทำแฮ็กมากขึ้นด้วยการเปลี่ยนแบบอักษรสำหรับappearanceFontUIAlertAction

สร้างหมวดหมู่สำหรับ UILabel

UILabel + FontAppearance.h

@interface UILabel (FontAppearance)

@property (nonatomic, copy) UIFont * appearanceFont UI_APPEARANCE_SELECTOR;

@end

UILabel + FontAppearance.m

@implementation UILabel (FontAppearance)

- (void)setAppearanceFont:(UIFont *)font
{
    if (self.tag == 1001) {
        return;
    }

    BOOL isBold = (self.font.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold);
    const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

    if (self.font.pointSize == 14) {
        // set font for UIAlertController title
        self.font = [UIFont systemFontOfSize:11];
    } else if (self.font.pointSize == 13) {
        // set font for UIAlertController message
        self.font = [UIFont systemFontOfSize:11];
    } else if (isBold) {
        // set font for UIAlertAction with UIAlertActionStyleCancel
        self.font = [UIFont systemFontOfSize:12];
    } else if ((*colors) == 1) {
        // set font for UIAlertAction with UIAlertActionStyleDestructive
        self.font = [UIFont systemFontOfSize:13];
    } else {
        // set font for UIAlertAction with UIAlertActionStyleDefault
        self.font = [UIFont systemFontOfSize:14];
    }
    self.tag = 1001;
}

- (UIFont *)appearanceFont
{
    return self.font;
}

@end

การใช้งาน:

เพิ่ม

[[UILabel appearanceWhenContainedIn:UIAlertController.class, nil] setAppearanceFont:nil];

ในการที่จะทำให้การทำงานทั้งหมดAppDelegate.mUIAlertController


ชื่อใน iOS 8.3 เป็น 13pt และเป็นตัวหนาดังนั้นฉันจึงเปลี่ยนเงื่อนไขเป็นif (self.font.pointSize == 13 && isBold) {
Andrew Raphael

UIAlertActionที่คุณกล่าวถึงการเปลี่ยนแปลงตัวอักษรสำหรับ แต่เท่าที่ฉันสามารถบอกได้ว่าUIAlertActionไม่ใช้ไฟล์UILabel. มันใช้NSStringไฟล์. github.com/nst/iOS-Runtime-Headers/blob/…ฉันไม่รู้ว่าคุณจะปรับแต่งฟอนต์สำหรับNSStringไฟล์.
peacetype

UIAlertAction ไม่ใช่คลาสมุมมองเลย เป็นคลาสนามธรรมที่อธิบายการกระทำ จากนั้นมุมมองจะถูกสร้างขึ้นภายใน UIAlertController คุณจึงตั้งค่าลักษณะที่ปรากฏใน UIAlertController
mangerlahn

10

ฉันกำลังใช้มัน

[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor blueColor]];

เพิ่มหนึ่งบรรทัด (AppDelegate) และใช้งานได้กับ UIAlertController ทั้งหมด


3
เนื่องจากตอนนี้เลิกใช้แล้วให้ใช้ [[UIView AppearanceWhenContainedInInstancesOfClasses: @ [[UIAlertController class]]] setTintColor: newColor]; แทน
Peter Johnson

8

สวิฟต์ 4

ตัวอย่างแบบอักษรที่กำหนดเองในชื่อเรื่อง สิ่งเดียวกันสำหรับส่วนประกอบอื่น ๆ เช่นข้อความหรือการกระทำ

    let titleAttributed = NSMutableAttributedString(
            string: Constant.Strings.cancelAbsence, 
            attributes: [NSAttributedStringKey.font:UIFont(name:"FONT_NAME",size: FONT_SIZE)]
    )

    let alertController = UIAlertController(
        title: "",
        message: "",
        preferredStyle: UIAlertControllerStyle.YOUR_STYLE
    )

    alertController.setValue(titleAttributed, forKey : "attributedTitle")
    present(alertController, animated: true, completion: nil)

5

นี่คือส่วนขยายสำหรับ Swift 4.1 และ Xcode 9.4.1:

extension UIAlertController{

func addColorInTitleAndMessage(color:UIColor,titleFontSize:CGFloat = 18, messageFontSize:CGFloat = 13){

    let attributesTitle = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: titleFontSize)]
    let attributesMessage = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: UIFont.systemFont(ofSize: messageFontSize)]
    let attributedTitleText = NSAttributedString(string: self.title ?? "", attributes: attributesTitle)
    let attributedMessageText = NSAttributedString(string: self.message ?? "", attributes: attributesMessage)

    self.setValue(attributedTitleText, forKey: "attributedTitle")
    self.setValue(attributedMessageText, forKey: "attributedMessage")

}}

4

ฉันเพิ่งเปลี่ยนUIAlertControllerไฟล์. นี่เป็นวิธีเดียวที่สมเหตุสมผลฉันคิดว่า:


เก่า

นี่คือวิธีการของฉันใน Swift ซึ่งรวบรวมข้อมูลมากมายจากคำตอบที่นี่

func changeAlert(alert: UIAlertController, backgroundColor: UIColor, textColor: UIColor, buttonColor: UIColor?) {
    let view = alert.view.firstSubview().firstSubview()
    view.backgroundColor = backgroundColor
    view.layer.cornerRadius = 10.0

    // set color to UILabel font
    setSubviewLabelsToTextColor(textColor, view: view)

    // set font to alert via KVC, otherwise it'll get overwritten
    let titleAttributed = NSMutableAttributedString(
        string: alert.title!,
        attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(17)])
    alert.setValue(titleAttributed, forKey: "attributedTitle")


    let messageAttributed = NSMutableAttributedString(
        string: alert.message!,
        attributes: [NSFontAttributeName:UIFont.systemFontOfSize(13)])
    alert.setValue(messageAttributed, forKey: "attributedMessage")


    // set the buttons to non-blue, if we have buttons
    if let buttonColor = buttonColor {
        alert.view.tintColor = buttonColor
    }
}

func setSubviewLabelsToTextColor(textColor: UIColor, view:UIView) {
    for subview in view.subviews {
        if let label = subview as? UILabel {
            label.textColor = textColor
        } else {
            setSubviewLabelsToTextColor(textColor, view: subview)
        }
    }
}

วิธีนี้ใช้ได้ผลในบางสถานการณ์อย่างสมบูรณ์แบบและในบางสถานการณ์ก็ล้มเหลวทั้งหมด (สีอ่อนจะไม่แสดงตามที่คาดไว้)


4

คุณสามารถใช้ไลบรารีภายนอกเช่นPMAlertControllerโดยไม่ต้องใช้วิธีแก้ปัญหาซึ่งคุณสามารถแทนที่ UIAlertController ที่ไม่สามารถปรับแต่งได้ของ Apple ด้วยการแจ้งเตือนที่ปรับแต่งได้อย่างยอดเยี่ยม

เข้ากันได้กับ Xcode 8, Swift 3 และ Objective-C

ตัวอย่าง PMAlertController


คุณสมบัติ:

  • [x] มุมมองส่วนหัว
  • [x] รูปภาพส่วนหัว (ไม่บังคับ)
  • [x] ชื่อเรื่อง
  • [x] ข้อความรายละเอียด
  • [x] การปรับแต่ง: แบบอักษรสีมิติข้อมูลและอื่น ๆ
  • [x] 1, 2 ปุ่ม (แนวนอน) หรือ 3+ ปุ่ม (แนวตั้ง)
  • [x] ปิดเมื่อกดปุ่ม
  • [x] รองรับฟิลด์ข้อความ
  • [x] การใช้งานที่คล้ายกันกับ UIAlertController
  • [x] Cocoapods
  • [x] คาร์เธจ
  • [x] แอนิเมชั่นกับ UIKit Dynamics
  • [x] ความเข้ากันได้ของ Objective-C
  • [x] รองรับ Swift 2.3 & Swift 3

PMAlertController อนุญาตให้ตัดคำเมื่อข้อความยาวในปุ่มการทำงานหรือไม่
zeeple

@zeeple พิจารณาว่าปุ่มการดำเนินการเป็นคลาสย่อยของ UIButton อะไรทำนองนั้น actionButton.titleLabel.lineBreakMode = NSLineBreakByWordWrappingใช้ได้ดี
Paolo Musolino

3

มีปัญหาในการตั้งค่าสีอ่อนในมุมมองหลังจากนำเสนอ แม้ว่าคุณจะทำในบล็อกเสร็จสิ้นของ presentViewController: ภาพเคลื่อนไหว: การเสร็จสิ้น: มันทำให้เกิดเอฟเฟกต์การกะพริบบนสีของชื่อปุ่ม นี่เป็นเรื่องที่เลอะเทอะไม่เป็นมืออาชีพและไม่เป็นที่ยอมรับอย่างสิ้นเชิง

โซลูชันอื่น ๆ ที่นำเสนอขึ้นอยู่กับลำดับชั้นมุมมองที่ยังคงอยู่ซึ่งเป็นสิ่งที่ Apple ไม่ชอบที่จะทำ คาดว่าโซลูชันเหล่านั้นจะล้มเหลวใน iOS รุ่นต่อ ๆ ไป

วิธีหนึ่งที่แน่นอนในการแก้ปัญหานี้และทำได้ทุกที่คือการเพิ่มหมวดหมู่ให้กับ UIAlertController และหมุน viewWillAppear

ส่วนหัว:

//
//  UIAlertController+iOS9TintFix.h
//
//  Created by Flor, Daniel J on 11/2/15.
//

#import <UIKit/UIKit.h>

@interface UIAlertController (iOS9TintFix)

+ (void)tintFix;

- (void)swizzledViewWillAppear:(BOOL)animated;

@end

การใช้งาน:

//
//  UIAlertController+iOS9TintFix.m
//
//  Created by Flor, Daniel J on 11/2/15.
//

#import "UIAlertController+iOS9TintFix.h"
#import <objc/runtime.h>

@implementation UIAlertController (iOS9TintFix)

+ (void)tintFix {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method method  = class_getInstanceMethod(self, @selector(viewWillAppear:));
        Method swizzle = class_getInstanceMethod(self, @selector(swizzledViewWillAppear:));
        method_exchangeImplementations(method, swizzle);});
}

- (void)swizzledViewWillAppear:(BOOL)animated {
    [self swizzledViewWillAppear:animated];
    for (UIView *view in self.view.subviews) {
        if (view.tintColor == self.view.tintColor) {
            //only do those that match the main view, so we don't strip the red-tint from destructive buttons.
            self.view.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
            [view setNeedsDisplay];
        }
    }
}

@end

เพิ่ม. pch (ส่วนหัวที่คอมไพล์ไว้ล่วงหน้า) ในโครงการของคุณและรวมหมวดหมู่:

#import "UIAlertController+iOS9TintFix.h"

ตรวจสอบให้แน่ใจว่าคุณลงทะเบียน pch ของคุณในโครงการอย่างถูกต้องและจะรวมเมธอดหมวดหมู่ในทุกคลาสที่ใช้ UIAlertController

จากนั้นในเมธอด didFinishLaunchingWithOptions ในแอพของคุณให้นำเข้าหมวดหมู่ของคุณและโทร

[UIAlertController tintFix];

และมันจะแพร่กระจายไปยังทุก ๆ อินสแตนซ์ของ UIAlertController ภายในแอพของคุณโดยอัตโนมัติไม่ว่าจะเปิดโดยรหัสของคุณหรือของใครก็ตาม

โซลูชันนี้ใช้ได้กับทั้ง iOS 8.X และ iOS 9.X และไม่มีการกะพริบของวิธีการหลังการนำเสนอที่เปลี่ยนสี นอกจากนี้ยังไม่เชื่อเรื่องพระเจ้าอย่างสมบูรณ์เกี่ยวกับลำดับชั้นมุมมองของมุมมองย่อยของ UIAlertController

แฮ็คแฮ็ค!


วิธีนี้ใช้ได้ผลเป็นส่วนใหญ่ อย่างไรก็ตามเมื่อหมุนอุปกรณ์สีจะกลับไปเป็นเหมือนเดิมก่อนที่จะหมุนวน
Dhiraj Gupta

Dhiraj ฉันเพิ่งทดสอบสิ่งนี้อีกครั้งในการตั้งค่าโครงการอย่างชัดเจนเพื่อสำรวจสิ่งที่คุณค้นพบและฉันไม่เห็นด้วย สีจะไม่ย้อนกลับไปแบบที่หมุนอยู่
ObiDan

ตรวจสอบการทำงานบน xcode 6.4 และ xcode 7.0 เรียกใช้เครื่องจำลองทุกรูปแบบของ 8.X และ 9.0 หากมีการร้องขอฉันจะวางโครงการบน github
ObiDan

คุณสามารถดำเนินโครงการต่อไปได้ แต่นี่คือสิ่งที่ฉันเห็นเกิดขึ้นกับฉัน มันยังไม่ทำงานบน iPad บนพื้นฐานความคิดวิธีการ swizzling ของคุณ แต่ผมก็สามารถที่จะทำให้การทำงานโดย swizzling viewDidLayoutSubviews แม้ว่า
Dhiraj Gupta

หากคุณสร้างโปรเจ็กต์ฉันสามารถส่งคำขอดึงข้อมูลด้วย swizzle viewDidLayoutSubviews ซึ่งเป็นสิ่งที่ฉันเพิ่งใช้และส่งในแอพรุ่นล่าสุดของฉันไปยัง App Store และคุณสามารถดูได้หรือไม่?
Dhiraj Gupta

3

กรุณาหานี้หมวดหมู่ ฉันสามารถเปลี่ยน FONT และสีของ UIAlertAction และ UIAlertController

ใช้:

UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil];
[appearanceLabel setAppearanceFont:yourDesireFont]];  

5
กรุณาวางรหัสที่นี่หรือใช้บริการที่ไม่ต้องการให้ผู้อื่นเข้าสู่ระบบ
Sulthan

3

ใน Swift 4.1 และ Xcode 10

//Displaying alert with multiple actions and custom font ans size
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)

let titFont = [NSAttributedStringKey.font: UIFont(name: "ArialHebrew-Bold", size: 15.0)!]
let msgFont = [NSAttributedStringKey.font: UIFont(name: "Avenir-Roman", size: 13.0)!]

let titAttrString = NSMutableAttributedString(string: "Title Here", attributes: titFont)
let msgAttrString = NSMutableAttributedString(string: "Message Here", attributes: msgFont)

alert.setValue(titAttrString, forKey: "attributedTitle")
alert.setValue(msgAttrString, forKey: "attributedMessage")

let action1 = UIAlertAction(title: "Action 1", style: .default) { (action) in
    print("\(String(describing: action.title))")
}

let action2 = UIAlertAction(title: "Action 2", style: .default) { (action) in
    print("\(String(describing: action.title))")
}

let okAction = UIAlertAction(title: "Ok", style: .default) { (action) in
    print("\(String(describing: action.title))")
}
alert.addAction(action1)
alert.addAction(action2)
alert.addAction(okAction)

alert.view.tintColor = UIColor.blue
alert.view.layer.cornerRadius = 40
// //If required background colour 
// alert.view.backgroundColor = UIColor.white

DispatchQueue.main.async(execute: {
    self.present(alert, animated: true)
})

คำตอบของคุณต้องมีการอัพเดตให้หรือself.present(alertController, animated: true) self.present(alert, animated: true)
Yash Bedi

@Yash Bedi ขอบคุณฉันอัปเดตคำตอบของฉันโปรดตรวจสอบอีกครั้ง
iOS

2

โซลูชัน / แฮ็คสำหรับ iOS9

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Test Error" message:@"This is a test" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"Alert View Displayed");
 [[[[UIApplication sharedApplication] delegate] window] setTintColor:[UIColor whiteColor]];
    }];

    [alertController addAction:cancelAction];
    [[[[UIApplication sharedApplication] delegate] window] setTintColor:[UIColor blackColor]];
    [self presentViewController:alertController animated:YES completion:^{
        NSLog(@"View Controller Displayed");
    }];

ฉันลองสิ่งนี้แล้ว โปรดทราบว่าคุณกำลังเปลี่ยนการตั้งค่าสีหน้าต่างอีกครั้งเมื่อมีการนำเสนอตัวควบคุมการแจ้งเตือน ฉันเห็นการเปลี่ยนสีกลับมาที่ตัวควบคุมการแจ้งเตือน ฉันเชื่อว่าจะต้องทำการเปลี่ยนกลับเมื่อมีการแตะการดำเนินการใด ๆ
Germán

ขอบคุณ @ Germánที่ชี้ให้เห็นว่า .. ทำการเปลี่ยนแปลงโค้ด ฉันกำลังจัดการการเปลี่ยนกลับใน AlertAction ณ ตอนนี้ .. แต่ใช่ฉันยอมรับว่าสามารถจัดการได้ในตัวจัดการ dimiss เช่นกัน
Akhilesh Sharma

1

ฉันทำงานให้กับ Urban Outfitters เรามีพ็อดโอเพนซอร์สURBNAlertที่เราใช้ในแอปทั้งหมดของเรา มันขึ้นอยู่กับUIAlertControllerแต่สามารถปรับแต่งได้สูง

ที่มาอยู่ที่นี่: https://github.com/urbn/URBNAlert

หรือเพียงแค่ติดตั้งข้างพ็อดโดยวางURBNAlertใน Podfile ของคุณ

นี่คือรหัสตัวอย่างบางส่วน:

URBNAlertViewController *uac = [[URBNAlertViewController alloc] initWithTitle:@"The Title of my message can be up to 2 lines long. It wraps and centers." message:@"And the message that is a bunch of text. And the message that is a bunch of text. And the message that is a bunch of text."];

// You can customize style elements per alert as well. These will override the global style just for this alert.
uac.alertStyler.blurTintColor = [[UIColor orangeColor] colorWithAlphaComponent:0.4];
uac.alertStyler.backgroundColor = [UIColor orangeColor];
uac.alertStyler.textFieldEdgeInsets = UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0);
uac.alertStyler.titleColor = [UIColor purpleColor];
uac.alertStyler.titleFont = [UIFont fontWithName:@"Chalkduster" size:30];
uac.alertStyler.messageColor = [UIColor blackColor];
uac.alertStyler.alertMinWidth = @150;
uac.alertStyler.alertMaxWidth = @200;
// many more styling options available 

[uac addAction:[URBNAlertAction actionWithTitle:@"Ok" actionType:URBNAlertActionTypeNormal actionCompleted:^(URBNAlertAction *action) {
      // Do something
}]];

[uac addAction:[URBNAlertAction actionWithTitle:@"Cancel" actionType:URBNAlertActionTypeCancel actionCompleted:^(URBNAlertAction *action) {
      // Do something
}]];

[uac show];

สิ่งนี้รองรับสไตล์ ActionSheet หรือไม่
Danpe

@Danpe มันไม่ได้เป็นเพียงการแจ้งเตือนเท่านั้น .. ที่ถูกกล่าวว่า .. หากสิ่งที่คุณต้องการสร้างปัญหาใน repo นั่นคือสิ่งที่เราได้พูดคุยเกี่ยวกับการเพิ่มการสนับสนุนก่อนหน้านี้
RyanG

1

ในการเปลี่ยนสีของปุ่มเดียวเช่น CANCEL เป็นสีแดงคุณสามารถใช้คุณสมบัติลักษณะนี้ที่เรียกว่า UIAlertActionStyle.destructive:

let prompt = UIAlertController.init(title: "Reset Password", message: "Enter Your E-mail :", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "Submit", style: .default) { (action) in
              //your code
}

let cancelAction = UIAlertAction.init(title: "Cancel", style: UIAlertActionStyle.destructive) { (action) in
                //your code
        }
        prompt.addTextField(configurationHandler: nil)
        prompt.addAction(okAction)
        prompt.addAction(cancelAction)
        present(prompt, animated: true, completion: nil);

1

สำหรับ iOS 9.0 ขึ้นไปให้ใช้รหัสนี้ใน app delegate

[[UIView appearanceWhenContainedInInstancesOfClasses:@[[UIAlertController class]]] setTintColor:[UIColor redColor]];

1

Swift 5.0

let titleAttrString = NSMutableAttributedString(string: "This is a title", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 17) as Any])
let messageAttrString = NSMutableAttributedString(string: "This is a message", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 13) as Any])

alertController.setValue(titleAttrString, forKey: "attributedTitle")
alertController.setValue(messageAttrString, forKey: "attributedMessage")

0

ค่อนข้างอึดอัด แต่ตอนนี้ใช้ได้กับฉันในการตั้งค่าสีพื้นหลังและสีข้อความ ผมพบว่ามันนี่

UIView * firstView = alertController.view.subviews.firstObject;
    UIView * nextView = firstView.subviews.firstObject;
    nextView.backgroundColor = [UIColor blackColor];

มันใช้งานได้กับสีพื้นหลัง แต่ไม่เคยเปลี่ยนสีของโทนสีนี่คือสิ่งที่ฉันสับสนเล็กน้อย
Akhilesh Sharma

0

ฉันได้สร้างวิธีการหนึ่งวัตถุประสงค์ -C

-(void)customAlertTitle:(NSString*)title message:(NSString*)message{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];

UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 270, 50)];
titleLabel.text = title;
titleLabel.font = [UIFont boldSystemFontOfSize:20];
titleLabel.numberOfLines = 2;
titleLabel.textColor = [UIColor redColor];
titleLabel.textAlignment = NSTextAlignmentCenter;

[subView addSubview:titleLabel];

UILabel *messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 270, 50)];
messageLabel.text = message;
messageLabel.font = [UIFont systemFontOfSize:18];
messageLabel.numberOfLines = 2;
messageLabel.textColor = [UIColor redColor];
messageLabel.textAlignment = NSTextAlignmentCenter;

[subView addSubview:messageLabel];

[alertView setValue:subView forKey:@"accessoryView"];
[alertView show];
}

Code wokring อย่างสมบูรณ์แบบบน Xcode 8.3.1 คุณสามารถปรับแต่งตามความต้องการ


0

ฉันแค่ใช้ความต้องการแบบนี้ดูเหมือนและระบบรายละเอียดจะแตกต่างกันเล็กน้อยดังนั้นเราจึง ... OC ตระหนักถึงการแจ้งเตือนและการห่อหุ้มหน้าต่างป๊อปอัพแผ่นงาน

บ่อยครั้งที่พบในการพัฒนาประจำวันจำเป็นต้องเพิ่มตัวเลขในการแจ้งเตือนหรือเปลี่ยนสีของปุ่มเช่นความต้องการ "ธรรมดา" ในปัจจุบันได้นำส่วนประกอบของระบบที่มีความคล้ายคลึงกันสูงและสามารถตอบสนองความต้องการของส่วนประกอบบรรจุภัณฑ์ที่กำหนดเองได้อย่างเต็มที่

Github: https://github.com/ReverseScale/RSCustomAlertView

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.