ios – 如何在UIAlertController的中心显示活动指示器?

前端之家收集整理的这篇文章主要介绍了ios – 如何在UIAlertController的中心显示活动指示器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前在屏幕上显示一个UIAlertController.警报的视图只应在警报的中心显示2个元素,一个标题和一个UIActivityIndi​​catorView.以下是显示警报及其元素的功能.
func displaySignUpPendingAlert() -> UIAlertController {
        //Create the UIAlertController
        let pending = UIAlertController(title: "Creating New User",message: nil,preferredStyle: .Alert)
        //Create the activity indicator to display in it.
        let indicator = UIActivityIndicatorView(frame: CGRectMake(pending.view.frame.width / 2.0,pending.view.frame.height / 2.0,20.0,20.0))
        indicator.center = CGPointMake(pending.view.frame.width / 2.0,pending.view.frame.height / 2.0)
        //Add the activity indicator to the alert's view
        pending.view.addSubview(indicator)
        //Start animating
        indicator.startAnimating()

        self.presentViewController(pending,animated: true,completion: nil)
        return pending
    }

但是,活动指示器不会显示在视图的中心,实际上它显示在屏幕的右下方,远离视图.这是什么原因?

编辑:我明白,我可以硬编码为指标的位置,但我希望警报工作在多个设备与多个屏幕尺寸和方向.

解决方法

创建视图时,请确保设置frame属性.
func displaySignUpPendingAlert() -> UIAlertController {
        //create an alert controller
        let pending = UIAlertController(title: "Creating New User",preferredStyle: .Alert)

        //create an activity indicator
        let indicator = UIActivityIndicatorView(frame: pending.view.bounds)
        indicator.autoresizingMask = [.FlexibleWidth,.FlexibleHeight]

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

        self.presentViewController(pending,completion: nil)

        return pending
}

到@ 62Shark:

let pending = UIAlertController(title: "Creating New User",preferredStyle: .Alert)

let indicator = UIActivityIndicatorView()
indicator.setTranslatesAutoresizingMaskIntoConstraints(false)
pending.view.addSubview(indicator)

let views = ["pending" : pending.view,"indicator" : indicator]
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[indicator]-(-50)-|",options: nil,metrics: nil,views: views)
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[indicator]|",views: views)
pending.view.addConstraints(constraints)

indicator.userInteractionEnabled = false
indicator.startAnimating()

self.presentViewController(pending,completion: nil)

猜你在找的iOS相关文章