Определите UIAlertViewController один раз и используйте его в разных классах в Objective-C - PullRequest
0 голосов
/ 21 декабря 2018

Я хочу узнать, как решить эту проблему.

//Modal.h

-(void)errorAlert : (NSString *)title : (NSString *)desc : (NSString *)buttonTitle;


//Modal.m

-(void)errorAlert: (NSString *)title : (NSString *)desc : (NSString *)buttonTitle{

    alert = [UIAlertController alertControllerWithTitle:title message:desc preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *ok = [UIAlertAction actionWithTitle:buttonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];

    [alert addAction:ok];

    [self presentViewController:alert animated:YES completion:nil];

}

Теперь я хочу использовать это errorAlert в других классах, чтобы мне не пришлось снова писать проверку для оповещения

//Login.m


#import "Modal.m"

@property (strong, nonatomic) Modal *modal;


-(void)viewDidLoad{

  _modal = [[Modal alloc] init];

}



//MARK: Submit Clicked

- (IBAction)submitClicked:(UIButton *)sender {


    // I want to use that method here.

}

Пожалуйста, предложите мне выход, чтобы я мог оптимизировать свой код в соответствии с форматом.

Ответы [ 2 ]

0 голосов
/ 21 декабря 2018

OBJECTIVE-C:

  1. In Alert.h
(void)showAlertWithTitle:(NSString *)title 
        message:(NSString* _Nullable)message 
        defaultPrompt:(NSString *)defaultPrompt 
        optionalPrompt:(NSString* _Nullable)optionalPrompt 
        defaultHandler:(nullable void(^)(UIAlertAction *))defaultHandler 
        optionalHandler:(nullable void(^)(UIAlertAction *))optionalHandler;
In Alert.m
    (void)showAlertWithTitle:(NSString *)title message:(NSString* _Nullable)message defaultPrompt:(NSString *)defaultPrompt optionalPrompt:(NSString* _Nullable)optionalPrompt defaultHandler:(nullable void(^)(UIAlertAction *))defaultHandler optionalHandler:(nullable void(^)(UIAlertAction *))optionalHandler {

    // Executing the method in the main thread, since its involving the UI updates.
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertAction actionWithTitle:defaultPrompt style:UIAlertActionStyleDefault handler:defaultHandler]];
    if (optionalPrompt) {
        [alert addAction:[UIAlertAction actionWithTitle:optionalPrompt style:UIAlertActionStyleCancel handler:optionalHandler]];
    }
    [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alert animated:true completion:nil];
}); }

SWIFT 4.2:

Просто создайте новый файл swift с именем Alert.swift и определите обобщенную версию AlertController в нем.Таким образом, вы можете использовать его в любом месте проекта, просто позвонив Alert.showErrorAlert("", title: "")

import UIKit
import os.log

class Alert {

    /// Display the given error message as an alert pop-up
    /// - parameter errorMessage: The error description
    /// - parameter title: The title of the error alert
    class func showErrorAlert(_ errorMessage: String, title: String?) {
        let alert = UIAlertController(title: title ?? "Error", message: errorMessage, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        guard let rootView = UIApplication.shared.keyWindow?.rootViewController else {
            os_log("Cannot show alert in the root view", log: .default, type: .error)
            return
        }
        rootView.present(alert, animated: true, completion: nil)
    }


}
0 голосов
/ 21 декабря 2018

Как уже упоминалось в комментариях, на самом деле это не выглядит лучшей реализацией.В любом случае, чтобы ответить на ваш вопрос: во-первых, подпись вашего метода должна быть исправлена ​​следующим образом

-(void)errorAlertWithTitle:(NSString *)title description:(NSString *)desc buttonTitle:(NSString *)buttonTitle fromViewController:(UIViewController *)viewController;

И его реализация

-(void)errorAlertWithTitle:(NSString *)title description:(NSString *)desc buttonTitle:(NSString *)buttonTitle fromViewController:(UIViewController *)viewController {
    alert = [UIAlertController alertControllerWithTitle:title message:desc preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:buttonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){}];
    [alert addAction:ok];
    [viewController presentViewController:alert animated:YES completion:nil];
}

Тогда вам просто нужно вызвать его вsubmitClicked

- (IBAction)submitClicked:(UIButton *)sender {
    [self.modal errorAlertWithTitle:@"The title" description:@"The description" buttonTitle:@"ButtonTitle" fromViewController:self];
}
...