UIBarButtonItem在旋转动画后帧发生更改

时间:2017-10-31 15:06:53

标签: ios iphone swift uinavigationbar swift4

我在自定义UIBarButtonItem中进行旋转动画时遇到问题。 enter image description here

我的代码如下:

类ViewController:UIViewController {

var bellIcon:UIBarButtonItem = UIBarButtonItem()

override func viewDidLoad() {
    super.viewDidLoad()        
    setupBellButton()
}

func setupBellButton(){
    let icon = UIImage(named: "Bell.png")
    let iconSize = CGRect(origin: CGPoint.zero, size: icon!.size)
    let iconButton = UIButton(frame: iconSize)
    iconButton.setBackgroundImage(icon, for: .normal)

    let badgeView = UIView(frame: CGRect(origin: CGPoint(x: iconButton.frame.maxX-10, y: iconButton.frame.minX), size: CGSize(width: 10, height: 10)))
    badgeView.layer.cornerRadius = 5
    badgeView.layer.borderColor = UIColor.red.cgColor
    badgeView.backgroundColor = UIColor.red
    badgeView.layer.masksToBounds = true
    badgeView.clipsToBounds = true

    let btnContainer = UIView(frame: CGRect(origin: CGPoint.zero, size: icon!.size))
    btnContainer.addSubview(iconButton)
    btnContainer.addSubview(badgeView)

    badgeView.transform = CGAffineTransform(scaleX: 0, y: 0)

    UIView.animate(withDuration: 1) {
        badgeView.transform = CGAffineTransform(scaleX: 1, y: 1)
    }
    bellIcon.customView = btnContainer

    iconButton.addTarget(self, action:#selector(bellIconTapped), for: .touchUpInside)

    navigationItem.rightBarButtonItem = bellIcon
    bellIcon.customView?.backgroundColor = UIColor.purple
}

@IBAction func bellIconTapped(_ sender: Any) {
    UIView.animate(withDuration: 0.3, animations: {

        self.bellIcon.customView!.transform =   CGAffineTransform(rotationAngle: -0.4)
    }) { (true) in
        UIView.animate(withDuration: 0.3, animations: {

            self.bellIcon.customView!.transform = CGAffineTransform(rotationAngle: 0.4)
        }, completion: { (true) in
            UIView.animate(withDuration: 0.4, animations: {
                self.bellIcon.customView!.transform = CGAffineTransform.identity

            })
        })
    }
}

}

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

我已经解决了iOS 10和11的上述问题,只需将常量添加到'bellIcon.customView'

我在'setupBellButton()'

的末尾添加了以下代码
    bellIcon.customView?.translatesAutoresizingMaskIntoConstraints = false

    let widthConstraint = bellIcon.customView?.widthAnchor.constraint(equalToConstant: 25.0)
    let heightConstraint = bellIcon.customView?.heightAnchor.constraint(equalToConstant: 25.0)

    bellIcon.customView?.addConstraints([widthConstraint!, heightConstraint!])

快乐编码!!!