以编程方式将指示器视图置于警报控制器中

center an indicator view in an alertcontroller programmatically

我试图以编程方式将 activity 指示器置于警报控制器的中心,但没有看到预期的结果。

尝试:

import NVActivityIndicatorView

public func displayActivityAlertWithCompletion(ViewController: UIViewController, pending: UIAlertController, completionHandler: @escaping ()->())
{

    //create an activity indicator
    let indicator = NVActivityIndicatorView(frame: CGRect(x: (pending.view.frame.width/2) - 25 , y: 0, width: 50, height: 50))


    //indicator.clipsToBounds = true
    indicator.type = .ballScaleMultiple
    indicator.autoresizingMask = \[.flexibleWidth, .flexibleHeight\]
    indicator.color = UIColor(rgba: Palette.loadingColour)



    //add the activity indicator as a subview of the alert controller's view
    pending.view.addSubview(indicator)
    indicator.isUserInteractionEnabled = false
    // required otherwise if there buttons in the UIAlertController you will not be able to press them
    indicator.startAnimating()



    ViewController.present(pending, animated: true, completion: completionHandler)
}

您遇到的问题出在这一行:

let indicator = NVActivityIndicatorView(frame: CGRect(x: (pending.view.frame.width/2) - 25 , y: 0, width: 50, height: 50))

此时您的 pending 警报控制器 尚未 显示,并且其框架未更新。

您必须在显示警报控制器后更新指标的 frame,例如您可以执行以下操作。

替换此行:

ViewController.present(pending, animated: true, completion: completionHandler)

有了这个:

ViewController.present(pending, animated: true, completion: {
    // update frame here:
    indicator.frame = CGRect(x: (pending.view.frame.width/2) - 25 , y: 0, width: 50, height: 50)
    // and manually call completionHandler:
    completionHandler()
})