在制作自定义UIActivityIndi​​catorView时遇到一些麻烦

时间:2016-10-15 16:37:46

标签: ios swift uiactivityindicatorview uianimation

我正在尝试以编程方式创建自定义活动指示器视图。问题是它永远不会开始动画。这是spinner.swift类的代码:

import UIKit

class spinner: UIActivityIndicatorView {

var flag = Bool()

override init(frame: CGRect) {

    super.init(frame: frame)
    self.flag = true
    self.isHidden = false

 }

required init(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func startAnimating() {

    self.animate()

}

func animate()
{

    if flag == true
    {

        UIView.animate(withDuration: 0.3, animations: {

            self.layer.setAffineTransform(CGAffineTransform(scaleX: 0.5, y: 1))

        }) { (success) in

            if success == true
            {

                UIView.animate(withDuration: 0.3, animations: {

                    self.layer.setAffineTransform(CGAffineTransform.identity)

                    }, completion: { (success) in

                        if success == true
                        {

                            self.animate()

                        }

                })

            }

         }


      }

  }

override func stopAnimating() {
    self.flag = false

}

override func draw(_ rect: CGRect) {

    let path = UIBezierPath(ovalIn: rect)
    UIColor.cyan.setStroke()
    path.stroke()
    UIColor.red.setFill()
    path.fill()

  }

}

这是viewDidLoad()中的代码,我在其中添加了微调器:

    let aiv = spinner(frame: CGRect(x: self.view.bounds.width/2-35, y: self.view.bounds.height/2-35, width: 70, height: 70))
    aiv.hidesWhenStopped = true
    self.view.addSubview(aiv)
    aiv.startAnimating()
    print(aiv.isAnimating)
    print(air)

我根本没有看到微调器,并在控制台中收到以下消息:

    false
    <spinner.spinner: 0x7f82b3e08240; baseClass = UIActivityIndicatorView; frame = (170 298.5; 35 70); transform = [0.5, 0, 0, 1, 0, 0]; hidden = YES; animations = { transform=<CABasicAnimation: 0x6080000364a0>; }; layer = <CALayer: 0x608000035120>>

根据日志,微调器被隐藏,这意味着它从未开始动画。

如果有人能够指出我出错的地方并提出可行的解决方案,那就太好了。 谢谢!

1 个答案:

答案 0 :(得分:1)

由于通话原因,您的问题出现了:
aiv.hidesWhenStopped = true
并且属性isAnimating返回false因为你重写了animate方法而没有使用基础方法。
在启动和停止自定义动画时,应在自定义类中设置此属性。
同样的情况是隐藏的时候。这应该由您在班上实施。
我还建议使用UIView作为内部带有UIActivityIndi​​cator的子类,因为如果你想启动ActivityIndi​​cator,那么AffineTransformation可能会相互破坏。