Подтвердить что ты не робот

Диалоговое окно "Подождите" в iOS8

Раньше у меня был "Подождите" диалог в моем приложении в течение длительного времени. Это было довольно просто, используя UIActivityIndicatorView и добавив его в UIAlertView.

Однако iOS8 представил UIAlertController. Можно ли добавить что-нибудь к нему, чтобы иметь аналогичный эффект? Есть ли другой способ сделать это с iOS8?

Я искал много сайтов и до сих пор не знаю, как это можно сделать с новым API.

Буду признателен за любые ответы - ссылки на библиотеки, учебные пособия и т.д., которые могут быть полезны.

Привет,

Матеуш

4b9b3361

Ответ 1

Вместо использования UIAlertController вы можете использовать пользовательский UIViewController, который представлен модально. Вот что я использую в Swift 2.0:

class ActivityViewController: UIViewController {

    private let activityView = ActivityView()

    init(message: String) {
        super.init(nibName: nil, bundle: nil)
        modalTransitionStyle = .CrossDissolve
        modalPresentationStyle = .OverFullScreen
        activityView.messageLabel.text = message
        view = activityView
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private class ActivityView: UIView {

    let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
    let boundingBoxView = UIView(frame: CGRectZero)
    let messageLabel = UILabel(frame: CGRectZero)

    init() {
        super.init(frame: CGRectZero)

        backgroundColor = UIColor(white: 0.0, alpha: 0.5)

        boundingBoxView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
        boundingBoxView.layer.cornerRadius = 12.0

        activityIndicatorView.startAnimating()

        messageLabel.font = UIFont.boldSystemFontOfSize(UIFont.labelFontSize())
        messageLabel.textColor = UIColor.whiteColor()
        messageLabel.textAlignment = .Center
        messageLabel.shadowColor = UIColor.blackColor()
        messageLabel.shadowOffset = CGSizeMake(0.0, 1.0)
        messageLabel.numberOfLines = 0

        addSubview(boundingBoxView)
        addSubview(activityIndicatorView)
        addSubview(messageLabel)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        boundingBoxView.frame.size.width = 160.0
        boundingBoxView.frame.size.height = 160.0
        boundingBoxView.frame.origin.x = ceil((bounds.width / 2.0) - (boundingBoxView.frame.width / 2.0))
        boundingBoxView.frame.origin.y = ceil((bounds.height / 2.0) - (boundingBoxView.frame.height / 2.0))

        activityIndicatorView.frame.origin.x = ceil((bounds.width / 2.0) - (activityIndicatorView.frame.width / 2.0))
        activityIndicatorView.frame.origin.y = ceil((bounds.height / 2.0) - (activityIndicatorView.frame.height / 2.0))

        let messageLabelSize = messageLabel.sizeThatFits(CGSizeMake(160.0 - 20.0 * 2.0, CGFloat.max))
        messageLabel.frame.size.width = messageLabelSize.width
        messageLabel.frame.size.height = messageLabelSize.height
        messageLabel.frame.origin.x = ceil((bounds.width / 2.0) - (messageLabel.frame.width / 2.0))
        messageLabel.frame.origin.y = ceil(activityIndicatorView.frame.origin.y + activityIndicatorView.frame.size.height + ((boundingBoxView.frame.height - activityIndicatorView.frame.height) / 4.0) - (messageLabel.frame.height / 2.0))
    }
}

Вы используете его следующим образом:

let activitiyViewController = ActivityViewController(message: "Loading...")
presentViewController(activitiyViewController, animated: true, completion: nil)

И это будет выглядеть так:

ActivityViewController

Ответ 2

Попробуйте это, я сделал несколько трюков...

Ниже код работает для меня в iPod iOS8beta5 + XCode6

UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                        message:@"Please wait\n\n\n"
                                 preferredStyle:UIAlertControllerStyleAlert];

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    spinner.center = CGPointMake(130.5, 65.5);
    spinner.color = [UIColor blackColor];
    [spinner startAnimating];
    [alert.view addSubview:spinner];
    [self presentViewController:alert animated:NO completion:nil];

enter image description here

Ответ 3

Swift 2.0:

 override func viewDidAppear(animated: Bool)
 {

  let alertController = UIAlertController(title: nil, message: "Please wait\n\n", preferredStyle: UIAlertControllerStyle.Alert)

  let spinnerIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)

  spinnerIndicator.center = CGPointMake(135.0, 65.5)
  spinnerIndicator.color = UIColor.blackColor()
  spinnerIndicator.startAnimating()

  alertController.view.addSubview(spinnerIndicator)
  self.presentViewController(alertController, animated: false, completion: nil)

}

После некоторого момента нам нужно скрыть предупреждение.

alertController.dismissViewControllerAnimated(true, completion: nil)

Ответ 4

Swift 3.0

Чтобы отобразить диалог выполнения:

let alertController = UIAlertController(title: nil, message: "Please wait\n\n", preferredStyle: .alert)

let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)

spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5)
spinnerIndicator.color = UIColor.black
spinnerIndicator.startAnimating()

alertController.view.addSubview(spinnerIndicator)
self.present(alertController, animated: false, completion: nil)

Чтобы отменить диалог выполнения:

alertController.dismiss(animated: true, completion: nil);

Ответ 5

Если вы хотите отображать заголовок и индикатор активности, и вы чувствуете себя авантюрно, вы можете взломать иерархию представлений AlertController. Ниже приведен код ниже 8.2. Однако это обычно не должно быть в производстве.

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

Класс UIAlertController предназначен для использования как есть и не поддерживает подклассы. Иерархия представления для этого класса является частной и не должна быть изменена.

@implementation AlertControllerWithActivityIndicator

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    UIView *scrollView = [self findViewByClassPrefix:@"_UIAlertControllerShadowedScrollView" inView:self.view];
    UIView *containerView = [scrollView.subviews firstObject];
    UILabel *titleLabel = containerView.subviews.firstObject;

    if(!titleLabel) {
        return;
    }

    if(!self.indicatorView) {
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.indicatorView.translatesAutoresizingMaskIntoConstraints = NO;
        [containerView addSubview:self.indicatorView];
        NSDictionary *views = @{ @"text": titleLabel, @"indicator": self.indicatorView };

        NSArray *constraints = [scrollView constraintsAffectingLayoutForAxis:UILayoutConstraintAxisVertical];
        for(NSLayoutConstraint *constraint in constraints) {
            if(constraint.firstItem == containerView && constraint.secondItem == titleLabel && constraint.firstAttribute == NSLayoutAttributeBottom) {
                constraint.active = NO;
            }
        }

        [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[text]-[indicator]-24-|" options:0 metrics:nil views:views]];
        [containerView addConstraint:[NSLayoutConstraint constraintWithItem:self.indicatorView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];

        [self.indicatorView startAnimating];
    }
}

- (UIView *)findViewByClassPrefix:(NSString *)prefix inView:(UIView *)view {
    for(UIView *subview in view.subviews) {
        if([NSStringFromClass(subview.class) hasPrefix:prefix]) {
            return subview;
        }

        UIView *child = [self findViewByClassPrefix:prefix inView:subview];
        if(child) {
            return child;
        }
    }
    return nil;
}

@end

Производит что-то вроде этого:

UIAlertController with activity indicator

Ответ 6

Кажется, что это невозможно сделать простым способом, используя только базовый API. Я решил использовать DTAlertView, который допускает такие модификации. Он работает так, как я хотел.

https://github.com/Darktt/DTAlertView

Ответ 7

Swift 3.1 версия кода @darksinge

import UIKit

class ActivityViewController: UIViewController {

    private let activityView = ActivityView()

    init(message: String) {
        super.init(nibName: nil, bundle: nil)
        modalTransitionStyle = .crossDissolve
        modalPresentationStyle = .overFullScreen
        activityView.messageLabel.text = message
        view = activityView
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private class ActivityView: UIView {

    let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
    let boundingBoxView = UIView(frame: CGRect.zero)
    let messageLabel = UILabel(frame: CGRect.zero)

    init() {
        super.init(frame: CGRect.zero)

        backgroundColor = UIColor(white: 0.0, alpha: 0.5)

        boundingBoxView.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
        boundingBoxView.layer.cornerRadius = 12.0

        activityIndicatorView.startAnimating()

        messageLabel.font = UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)
        messageLabel.textColor = UIColor.white
        messageLabel.textAlignment = .center
        messageLabel.shadowColor = UIColor.black
        messageLabel.shadowOffset = CGSize(width: 0.0, height: 1.0)
        messageLabel.numberOfLines = 0

        addSubview(boundingBoxView)
        addSubview(activityIndicatorView)
        addSubview(messageLabel)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        boundingBoxView.frame.size.width = 160.0
        boundingBoxView.frame.size.height = 160.0
        boundingBoxView.frame.origin.x = ceil((bounds.width / 2.0) - (boundingBoxView.frame.width / 2.0))
        boundingBoxView.frame.origin.y = ceil((bounds.height / 2.0) - (boundingBoxView.frame.height / 2.0))

        activityIndicatorView.frame.origin.x = ceil((bounds.width / 2.0) - (activityIndicatorView.frame.width / 2.0))
        activityIndicatorView.frame.origin.y = ceil((bounds.height / 2.0) - (activityIndicatorView.frame.height / 2.0))

        let messageLabelSize = messageLabel.sizeThatFits(CGSize(width:160.0 - 20.0 * 2.0, height: CGFloat.greatestFiniteMagnitude))
        messageLabel.frame.size.width = messageLabelSize.width
        messageLabel.frame.size.height = messageLabelSize.height
        messageLabel.frame.origin.x = ceil((bounds.width / 2.0) - (messageLabel.frame.width / 2.0))
        messageLabel.frame.origin.y = ceil(activityIndicatorView.frame.origin.y + activityIndicatorView.frame.size.height + ((boundingBoxView.frame.height - activityIndicatorView.frame.height) / 4.0) - (messageLabel.frame.height / 2.0))
    }
}