Ezi00 Ezi00 - 3 months ago 31
Swift Question

UISearchBar showsCancelButton animation complete

I need to know when the cancel button of the UISearchBar has finished his animation after calling

searchBar.setShowsCancelButton(false, animated: true)


I've tried this

UIView.animateWithDuration(3, animations: {
self.searchBarView.searchBar.showsCancelButton = false
}, completion: {finished in
print(finished)
})


but the completion block gets triggered immediatly, any solution would be appreciated

Answer

You can use layoutIfNeeded() to update view in UIView.animateWithDuration(...)

try this code:

import UIKit

class ViewController: UIViewController {

@IBOutlet var searchBar: UISearchBar!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func touchUpInside(sender: UIButton) {
    searchBar.showsCancelButton = !searchBar.showsCancelButton
    UIView.animateWithDuration(3, animations: {
        self.searchBar.layoutIfNeeded()
        }, completion: {finished in
            print("Animation finished")
    })
}
}

and storyboard: enter image description here

Comments