UISearchBar stretches text when it begins editing

余生长醉 提交于 2019-12-12 08:02:34

问题


I have an instance of a UISearchBar added to the title view of a UINavigationBar. When there is text already set and the search bar starts editing it resizes its contents to allow space for the Cancel button, although, the resulting animation stretches the text, as showed in the gif below

Is there anything that can be done to avoid this defect effect? I have tried to remove the text and then to add it back a few moments later, although it works, it is not an elegant solution.

Update


Based on @Paruru's answer I tried to anticipate the animation of the Cancel button and it doesn't look bad. What I did is that I force the presentation of the Cancel button on 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
    }

}

The end result is what I want to achieve, the animation without the text being stretched. I consider this to be a workaround, and so I'll wait for other answers as this code might not be future proof.


回答1:


Your updated solution works well, except it stops the "Search" placeholder from being animated to the left when the Cancel button appears while there is no text. Checking searchBar.text restores the animation:

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
}

I suspect this may only be an issue for the Minimal UISearchBarStyle.




回答2:


- (void)setShowsCancelButton:(BOOL)showsCancelButton animated:(BOOL)animated NS_AVAILABLE_IOS(3_0);

Just call the method without animated.

if (!self.isShowCancelBtn) {
    [self.searchBar setShowsCancelButton:YES animated:NO];
    self.isShowCancelBtn = YES;
}else{
    [self.searchBar setShowsCancelButton:NO animated:NO];
    self.isShowCancelBtn = NO;
}


来源:https://stackoverflow.com/questions/31846311/uisearchbar-stretches-text-when-it-begins-editing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!