ios - UISearchBar 在开始编辑时拉伸(stretch)文本

标签 ios swift uikit uisearchbar

我有一个 UISearchBar 实例添加到 UINavigationBar 的标题 View 。当已经设置了文本并且搜索栏开始编辑时,它会调整其内容的大小以便为“取消”按钮留出空间,尽管如此,生成的动画会拉伸(stretch)文本,如下面的 gif 所示

enter image description here

有什么办法可以避免这种缺陷效应吗?我曾尝试删除文本,然后稍后再将其添加回来,尽管它可以工作,但这不是一个优雅的解决方案。

更新


根据@Paruru 的回答,我尝试预测 Cancel 按钮的动画,它看起来不错。我所做的是强制显示 searchBarShouldBeginEditing:

上的 Cancel 按钮
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
    }

}

最终结果是我想要实现的,没有文本被拉伸(stretch)的动画。我认为这是一种解决方法,因此我将等待其他答案,因为此代码可能无法满足 future 需求。

最佳答案

您更新后的解决方案运行良好,除了当“取消”按钮出现且没有文本时,它会阻止“搜索”占位符向左移动。检查 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 的问题。

关于ios - UISearchBar 在开始编辑时拉伸(stretch)文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846311/

相关文章:

ios - 在 iOS 中控制可访问性语音读出数字

ios - 实现Apple TV collectionview水平无限滚动

ios - UIViewPropertyAnimator 反向动画

iphone - 如何在 UIView 和 EAGLView 之间进行混合?

ios - 用 UIGraphicsImageRenderer 的 jpegData 替换 UIImageJPEGRepresentation

ios - 删除核心数据中的对象,无法匹配 Swift 数组元素类型

ios - 检查单元格是否完全显示在 Collection View 中

ios - 核心数据 - 在一对多关系中分配值

swift - 使用 Swift 获取核心数据实体

parsing - 从 TableView 转到 View Controller