UISearchBar 显示取消按钮的动画完成。

3
我需要知道在调用UISearchBar的取消按钮后,它的动画何时完成。
searchBar.setShowsCancelButton(false, animated: true)

我尝试过这个

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

但完成块立即触发,希望能得到任何解决方案。

使用闭包表达式不仅仅用于print(finished)。你可以添加一个成员变量'cancelDoneAnimating'并在闭包内将其设置为true。也许这不是最有效的方法,但另一个函数可以访问该成员变量来检查状态。 - NonCreature0714
如果我在闭包中添加一个成员,并将其设置为true,然后编写一个函数,在成员值变为true时触发该函数,为什么这个函数会在动画结束时被调用?(考虑完成块立即触发) - Azephiar
我理解你的意思。我想丑陋的解决方案是在闭包中添加与动画相同长度的延迟,然后将成员设置为true。 - NonCreature0714
1个回答

2
您可以使用layoutIfNeeded()在UIView.animateWithDuration(...)中更新视图。
试试这段代码:
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")
    })
}
}

和Storyboard相关:

在这里输入图片描述

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接