如何将进度条添加到UIAlertController?

Nik*_*Nik 12 ios progress-bar swift uialertcontroller

我想在swift iOS 8 UIAlertController中添加进度条.这可能吗?有没有办法继承UIAlertController并添加progres栏并连接一些委托函数?

谢谢

coy*_*yer 19

如果您只需要一个进度条,只需将其添加为子视图,如下所示:

//  Just create your alert as usual:
let alertView = UIAlertController(title: "Please wait", message: "Need to download some files.", preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

//  Show it to your users
present(alertView, animated: true, completion: {
    //  Add your progressbar after alert is shown (and measured)
    let margin:CGFloat = 8.0
    let rect = CGRect(x: margin, y: 72.0, width: alertView.view.frame.width - margin * 2.0 , height: 2.0)
    self.progressView = UIProgressView(frame: rect)
    self.progressView!.progress = 0.5
    self.progressView!.tintColor = self.view.tintColor
    alertView.view.addSubview(self.progressView!)
})
Run Code Online (Sandbox Code Playgroud)

调整大小的UIAlertController内容非常困难,但对于进度条,这应该可以解决问题.

  • 您只需更改"progressView.progress"即可.定义"var progressView:UIProgressView?"可能更清楚.外部(不在完成块中)作为可选项,然后设置"progressView?.progress = 0.123". (2认同)

小智 5

自动布局的解决方案:

    UIAlertController *alertCtr = [UIAlertController alertControllerWithTitle:@"Test" message:@"50%" preferredStyle:UIAlertControllerStyleAlert];
    [alertCtr addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        // Do things
    }]];

    UIView *alertView = alertCtr.view;

    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectZero];
    progressView.progress = 0.5;
    progressView.translatesAutoresizingMaskIntoConstraints = false;
    [alertView addSubview:progressView];


    NSLayoutConstraint *bottomConstraint = [progressView.bottomAnchor constraintEqualToAnchor:alertView.bottomAnchor];
    [bottomConstraint setActive:YES];
    bottomConstraint.constant = -45; // How to constraint to Cancel button?

    [[progressView.leftAnchor constraintEqualToAnchor:alertView.leftAnchor] setActive:YES];
    [[progressView.rightAnchor constraintEqualToAnchor:alertView.rightAnchor] setActive:YES];

    [self presentViewController:alertCtr animated:true completion:nil];
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述