自定义活动指示器不居中

时间:2015-09-14 16:49:32

标签: ios swift uiactivityindicatorview

我使用来自github的mownier的MONActivityIndi​​cator:https://github.com/mownier/MONActivityIndicatorView

这就是我设置指标的方法:

var activity = MONActivityIndicatorView()

activity.numberOfCircles = 5
activity.radius = 10
activity.internalSpacing = 3
activity.duration = 0.5
activity.delay = 0.3
activity.center = self.view.center

self.view.addSubview(activity)

activity.startAnimating()  

问题在于指示器没有显示在中心但在视图的右上角,为什么会这样?

1 个答案:

答案 0 :(得分:3)

您可以将约束添加到活动视图中,并使其成为演示项目的中心。

这是swift中的那个函数:

func placeAtTheCenterWithView(view: UIView) {

    self.view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))

    self.view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
}

从代码中删除此行:

activity.center = self.view.center

您的最终代码将是:

var activity = MONActivityIndicatorView()

activity.numberOfCircles = 5
activity.radius = 10
activity.internalSpacing = 3
activity.duration = 0.5
activity.delay = 0.3
self.view.addSubview(activity)
self.placeAtTheCenterWithView(activity)  //center it with constraint.
activity.startAnimating()

让它成为中心的另一种方法是在主线程中这样做:

dispatch_async(dispatch_get_main_queue()) {
    activity.center = self.view.center
}