animationUISearchBar框架的宽度
是否可以animationUISearchBar的框架宽度? 我发现,当我应用uiviewanimation来扩大search栏的范围时,它会立即popup最终结果,就好像对象内部正在控制它的animation效果,而不是让我自己animation顺利地应用。
如果我animation的位置它移动平稳,但我怀疑文本input调整根据取消button的存在可能意味着我们没有公共访问animation宽度通过UIViewanimation。 下面的示例代码片段从x = 0滑动到100,但popup宽度为600像素宽。
CGRect searchBarFrame = self.searchViewController.searchBar.frame; searchBarFrame.origin.x = 100; searchBarFrame.size.width = 600; [UIView animateWithDuration:1.0 delay:0.0 options:0 animations:^{ self.searchViewController.searchBar.frame = searchBarFrame; } completion:^(BOOL completion){ }];
由于内部视图强制resize以忽略animation,所以UISearchBar有一个“问题”。 但是,这可以通过使用 – layoutSubviews来克服。 我在下面的项目中包含了扩展和合同代码
[UIView animateWithDuration:.3 animations:^ { CGRect newBounds = locationSearch.frame; newBounds.size.width += 215; //newBounds.size.width -= 215; to contract locationSearch.frame = newBounds; [locationSearch layoutSubviews]; }];
希望这可以帮助。
仅供参考,您可以使用UIViewAnimationOption
而不是显式调用layoutsubviews
,所以代码看起来像这样..
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{ //Set the frame you want to the search bar } completion:^(BOOL finished) { }];
这就是如何迅速克服左侧的扩大
(当用户开始/结束编辑时,这段代码会放大/缩小左边93像素的search栏)
- SharedNavigationbBar是实现UISearchBarDelegate的UIView
- searchBarWidth是一个限制UISearchBar宽度的出口
- 故事板或nib文件中必须存在自动布局约束,以允许调整左侧的大小。 在这种情况下,最左边的组件是一个UIButton 。
- 添加下面的代码作为扩展或在您的类内执行animationresize。
extension SharedNavigationBar: UISearchBarDelegate { //amount of pixels to enlarge to the left private var offsetSearchBarLeft:CGFloat { get { return 93 } } ///Enlarges search bar func searchBarTextDidBeginEditing(searchBar: UISearchBar) { self.animateSearchBar(self.searchBar, enlarge: true) } ///Shrinks search bar func searchBarTextDidEndEditing(searchBar: UISearchBar) { self.animateSearchBar(self.searchBar, enlarge: false) } //shrinks or enlarge the searchbar (this will be the function to call inside the animation) private func animateSearchBar(searchBar:UISearchBar, enlarge:Bool) { ///Important here, for this to work, the option and the searchbar size must be handled this way UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.LayoutSubviews, animations: { [weak self] () -> Void in let multiplier: CGFloat = enlarge ? 1 : -1 let origin = searchBar.frame.origin.x + self!.offsetSearchBarLeft * multiplier let width = searchBar.frame.width + self!.offsetSearchBarLeft * multiplier //This Block of code, setting the new frame, needs to be inside the animation in order to work var newBounds:CGRect = searchBar.frame; newBounds.origin.x = origin newBounds.size.width = width //Sets the new frame self?.searchBarWidth.constant = width searchBar.frame = newBounds }, completion: nil) } }