我试图在下载图像时在每个集合视图单元格中放置一个UIActivityIndicatorView。我把它出现在每个细胞中,但它拒绝自我中心。它停留在左上角。我怎样才能让它正确居中?
以下是我的表现:
extension UIView {
func showActivityIndicator(onView: UIView, withIndicator: UIActivityIndicatorView) {
withIndicator.frame = CGRect(x: onView.frame.midX - 20, y: onView.frame.midY - 20, width: 40, height: 40)
withIndicator.activityIndicatorViewStyle = .whiteLarge
withIndicator.center = onView.center
onView.addSubview(withIndicator)
withIndicator.startAnimating()
}
}
我在cellForItemAtIndexPath中调用该函数,如:
showActivityIndicator(onView: cell.contentView, withIndicator: activityInd)
但是我所做的一切都不会从左上角移动它。有什么建议吗?
答案 0 :(得分:5)
试试这个
withIndicator.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
答案 1 :(得分:2)
您需要添加约束以使其居中。例如,使用NSLayoutAnchor。
您需要将translatesAutoresizingMaskIntoConstraints
设置为false
,以设置约束。并在将其添加到视图后设置约束(代码注释中的提示):
extension UIView {
func showActivityIndicator(onView: UIView, withIndicator: UIActivityIndicatorView) {
withIndicator.frame = CGRect(x: onView.frame.midX - 20, y: onView.frame.midY - 20, width: 40, height: 40)
withIndicator.activityIndicatorViewStyle = .whiteLarge
// set translatesAutoresizingMaskIntoConstraints to false to set your constraints
withIndicator.translatesAutoresizingMaskIntoConstraints = false
onView.addSubview(withIndicator)
withIndicator.startAnimating()
// add the constraints to center the indicator
withIndicator.centerXAnchor.constraint(equalTo: onView.centerXAnchor).isActive = true
withIndicator.centerYAnchor.constraint(equalTo: onView.centerYAnchor).isActive = true
}
}
答案 2 :(得分:0)
我建议使用约束(又称自动布局):
indicator.translatesAutoresizingMaskIntoConstraints = false
"your cell".addSubview(indicator)
let widthConstraint = NSLayoutConstraint(item: indicator, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 250)
let heightConstraint = NSLayoutConstraint(item: indicator, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
let xConstraint = NSLayoutConstraint(item: indicator, attribute: .CenterX, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterX, multiplier: 1, constant: 0)
let yConstraint = NSLayoutConstraint(item: indicator, attribute: .CenterY, relatedBy: .Equal, toItem: self.tableView, attribute: .CenterY, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([widthConstraint, heightConstraint, xConstraint, yConstraint])