1

I am facing issue in frame while doing rotation animation in custom UIBarButtonItem. enter image description here

My code is as follow:

class 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

            })
        })
    }
}

}

Thanks in advance!!!

Chetan A
  • 73
  • 8

1 Answers1

0

I have resolved the above issue for both iOS 10 and 11 by simply adding the constant to the 'bellIcon.customView'

I have added following code at the end of the '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!])

Happy Coding!!!

Chetan A
  • 73
  • 8