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];

이제 제목과 메시지 글꼴, 색상, 크기 등을 변경하고 싶습니다. 이를 수행하는 가장 좋은 방법은 무엇입니까?

편집 : 전체 코드를 삽입해야합니다. iOS 버전에 맞는 경고를 표시 할 수있는 UIView 카테고리를 만들었습니다.

@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를 사용하는 경향이있는 경우. 그리고 무슨 일이야의 응답 아래에 ..에
— 야쉬 베디

답변:


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

XCode 10 이상에서 Swift 4.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 2014 년

2
UIAlertController 버튼에 추가 할 수있는 모든 사용자 정의는 무엇입니까 ??
— Aanchal Chaurasia

1
감사! 작은 질문이 있습니다. 속성 타일 및 메시지와 함께 사용자 지정 글꼴 및 색상을 사용할 수 있습니다 UIAlertController. 어떻게 똑같이 할 수 UIAlertAction있습니까?
— p0lAris

72
개인 API를 사용하므로 앱 스토어에이 기능을 출시 할 계획이 없길 바랍니다. 진지하게, 나는이 답변이 실제로 '답변'이 아닌데 왜 Stackoverflow에서 받아 들여 지는지 모르겠습니다. 이는 애플리케이션 스토어에 게시하는 것과 관련하여 벗어나지 않을 수도있는 해킹입니다.
— TheCodingArt

3
앱 스토어에서 앱을 출시하는 경우 일부 비공개 API 사용은 Apple에서 허용하지만 사용자의 시스템 / 개인 정보에 해를 끼치거나 영향을 미칠 수있는 API를 사용해서는 안됩니다. 따라서 아마도이 답변은 이것으로 인해 많은 사람들이 받아 들일 수 있습니다. 그리고 아마도 앱 스토어에 영향을 미치지 않을 수도 있습니다. 이것을 사용한 사람이 앱이 거부되지 않았 음을 확인할 수 있습니까?
— Mehul Thakkar

66

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 2015 년

iOS 9에서이 문제에 대한 Swift 답변과 해결 방법을 추가해 주셔서 감사합니다.
— peacetype

3
탭하고 손가락을 아래로 끌면 다시 기본 색상으로 바뀝니다. 어떤 생각?
— msmq

이것은 정말로 여기에서 유일하게 괜찮은 대답입니다.
— TheCodingArt

47

다음 코드를 사용하여 버튼 텍스트의 색상을 변경할 수 있습니다.

alertC.view.tintColor = your color;

아마도 이것이 당신을 도울 것입니다.


@esilver iOS9에서 작동하는 솔루션을 찾았습니까?
— Ash

1
나는하지 않았다. Apple에서 버그 보고서 # 22391695를 작성했습니다.
— esilver 2015-08-26

1
이것에 대한 추가 정보. ... 당신이 긴 목록 항목에서 스크롤 할 때, 당신은 스크롤을 터치 한 파란색 될 것 같다
— Bejil

3
이 작업은 iOS9 및 9.1의 UIAlertController에서 작동하지 않습니다. 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 사용자 정의 글꼴, 크기 및 색상


죄송합니다, 시작입니다. 기능에 필요한 경우 난 ... 당신에게 알려줄 것입니다
— 아이폰 OS

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
"OK"버튼은 어떻습니까? 사용자 정의 할 수 있습니까?
— Hassan Taleb 2016

@HassanTaleb 버튼을 사용자 정의하는 좋은 방법을 찾지 못했습니다. tintColor에서 view또는을 (를) 통해 설정할 수 appearanceWhenContainedIn있지만 터치하자마자 색조가 사라집니다. 그래도 여전히 답변을 찾고 있습니다.
— Robert Chen

@AbdulMomen عبدالمؤمن 어떤 오류 메시지가 표시됩니까? 코드 조각은 FontAwesome이 이미 설정되어 있다고 가정합니다.
— Robert Chen

1
@RobertChen은 문제를 해결하기 위해 그냥 색조를 넣습니다 : self.presentViewController(alertController, animated: true, completion: nil), "OK"버튼의 글꼴을 변경할 수 있습니까?
— Hassan Taleb 2016

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.

PS iOS 버전 대신 수업 가용성을 더 잘 확인하십시오.

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

작동하지만 이런 식으로 메시지와 제목에 대해 다른 크기를 가질 수 없습니다.
— Libor Zapletal 2014 년

이것은 작동하지만 작업을 클릭하면 글꼴이 원래 크기로 되돌아갑니다? 당신에게 이런 일이 일어나나요?
— Larry

@Larry 같은 문제가 있는데 처리 할 방법을 찾지 못했습니다.
— 알래스카

12

UIAppearance프로토콜을 사용하십시오 . 의 appearanceFont글꼴을 변경하려면 더 많은 해킹 을 수행하십시오 UIAlertAction.

카테고리 만들기 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.m이 모두를 위해 작동하도록합니다 UIAlertController.


아이폰 OS 8.3의 제목은 I가 조건을 변경 있도록 13pt과 대담if (self.font.pointSize == 13 && isBold) {
— 앤드류 라파엘

의 글꼴 변경에 대해 언급하셨습니다 UIAlertAction. 그러나 내가 말할 수 UIAlertAction있는 한 UILabel. 그것은 NSString. github.com/nst/iOS-Runtime-Headers/blob/… .NET 용 글꼴을 사용자 지정하는 방법을 모르겠습니다 NSString.
— peacetype

UIAlertAction은 전혀 뷰 클래스가 아닙니다. 액션을 설명하는 추상 클래스입니다. 그러면 뷰 자체가 UIAlertController 내에서 생성됩니다. 따라서 UIAlertController에 포함 된 모양을 설정합니다.
— mangerlahn

12

Swift 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"사용에 대해 앱을 거부 할 수 있습니다. 아니요, 앱을 출시하지 않았습니다.
— 거진 더 싱

이것은 Apple 개발자 사이트에 언급되어 있습니다.-> Important UIAlertController 클래스는있는 그대로 사용하기위한 것이며 서브 클래 싱을 지원하지 않습니다. 이 클래스의보기 계층은 비공개이며 수정해서는 안됩니다.
— 거진 더 싱

알겠습니다 보스 감사합니다.
— Yash Bedi

@Darkglow 오류를 언급하십시오. 빠른 5.1로 동일한 코드를 성공적으로 빌드 할 수 있습니다
— Gurjinder Singh

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 와 같은 외부 라이브러리를 사용할 수 있습니다 . 여기서 Apple의 사용자 지정이 불가능한 UIAlertController를 매우 사용자 지정 가능한 경고로 대체 할 수 있습니다.

Xcode 8, Swift 3 및 Objective-C와 호환

PMAlertController 예제


풍모:

  • [x] 헤더보기
  • [x] 헤더 이미지 (선택 사항)
  • [x] 제목
  • [x] 설명 메시지
  • [x] 사용자 정의 : 글꼴, 색상, 치수 등
  • [x] 1, 2 버튼 (수평) 또는 3+ 버튼 (수직)
  • [x] 버튼을 누르면 닫힘
  • [x] 텍스트 필드 지원
  • [x] UIAlertController와 유사한 구현
  • [x] 코코아 포드
  • [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 : animated : completion :의 완료 블록에서 수행하더라도 버튼 제목의 색상에 깜박임 효과가 발생합니다. 이것은 조잡하고 비전문적이고 완전히 용납 할 수 없습니다.

제시된 다른 솔루션은 정적으로 남아있는 뷰 계층 구조에 따라 달라지며, 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 2015

Dhiraj, 방금 프로젝트 설정에서 이것을 다시 테스트하여 여러분의 결과를 탐색했지만 동의하지 않습니다. 색조가 회전하는 방식으로 돌아 가지 않습니다.
— ObiDan 2015

xcode 6.4 및 xcode 7.0에서 기능이 확인되었습니다. 8.X 및 9.0의 모든 변형 시뮬레이터를 실행합니다. 요청하면 프로젝트를 github에 올릴 것입니다.
— ObiDan 2015

계속해서 프로젝트를 진행할 수 있습니다.하지만 이것이 제게 일어나는 일입니다. iPad에서도 작동하지 않았습니다. 당신의 방법 스위 즐링 아이디어를 바탕으로, 그러나, 나는 이었다 하지만, 스위 즐링 viewDidLayoutSubviews에 의해 작동 할 수.
— Dhiraj Gupta 2015

프로젝트를 올리면 viewDidLayoutSubviews swizzle으로 풀 리퀘스트를 제출할 수 있습니다. 이것은 제가 방금 사용하고 내 앱의 최신 빌드에서 App Store에 제출 한 것입니다. 당신은 볼 수 있습니까?
— Dhiraj Gupta

3

이 카테고리를 찾으십시오 . UIAlertAction 및 UIAlertController의 FONT 및 색상을 변경할 수 있습니다.

사용하다:

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 2015 년

지적 해 주신 @ Germán에게 감사드립니다 .. 코드를 변경했습니다. 지금의로 AlertAction에서 되돌리기를 처리하고 ..하지만 그래 난 그게 너무 dimiss 핸들러에서 처리 할 수 동의
— Akhilesh Sharma는

1

저는 Urban Outfitters에서 일합니다. URBNAlert모든 앱에서 사용한 오픈 소스 포드가 있습니다. 을 기반으로 UIAlertController하지만 고도로 사용자 정의 할 수 있습니다.

출처 : https://github.com/urbn/URBNAlert

또는 URBNAlertPodfile 에 배치하여 Pod별로 설치 하십시오.

다음은 몇 가지 샘플 코드입니다.

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 이상의 경우 앱 델리게이트에서이 코드를 사용하세요.

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

1

스위프트 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];
}

Xcode 8.3.1에서 완벽하게 작동하는 코드. 요구 사항에 따라 사용자 지정할 수 있습니다.


0

난 그냥 이런 종류의 수요를 사용하고, 겉보기와 시스템, 세부 사항이 약간 다르기 때문에 ... OC는 Alert 및 Sheet 팝업 창 캡슐화를 실현했습니다.

일상적인 개발에서 종종 발생하는 경고에 숫자를 추가하거나 "단순"수요와 같은 버튼 색상을 변경해야합니다. 오늘날에는 매우 유사한 시스템 구성 요소를 가져오고 맞춤형 포장 구성 요소의 수요를 완전히 충족 할 수 있습니다.

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

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.