ios – UISearchBar在开始编辑时会拉伸文本

我有一个UISearchBar的实例添加到UINavigationBar的标题视图中.当已经设置了文本并且搜索栏开始编辑时,它会调整其内容的大小以允许“取消”按钮的空间,但是,生成的动画会拉伸文本,如下面的gif所示

有什么办法可以避免这种缺陷效应吗?我试图删除文本然后稍后添加它,虽然它有效,但它不是一个优雅的解决方案.

更新

根据@ Paruru的回答,我试着预测取消按钮的动画,看起来并不坏.我所做的就是强制在searchBarShouldBeginEditing上显示“取消”按钮:

extension SearchViewController: UISearchBarDelegate {

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        if searchBar.text?.isEmpty == false {
            // This avoids the text being stretched by the UISearchBar.
            searchBar.setShowsCancelButton(true,animated: true)
        }
        return true
    }

}

最终结果是我想要实现的,没有文本被拉伸的动画.我认为这是一种解决方法,所以我会等待其他答案,因为这些代码可能不会成为未来的证据.

解决方法

您更新的解决方案效果很好,除了在没有文本时出现“取消”按钮时,“搜索”占位符停止向左设置动画.检查searchBar.text可恢复动画:
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    // This avoids the text being stretched by the UISearchBar.
    if searchBar.text?.isEmpty == false {
        searchBar.setShowsCancelButton(true,animated: true)
    }
    return true
}

我怀疑这可能只是Minimal UISearchBarStyle的一个问题.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...