是否可以为UISearchBar的帧宽设置动画?我发现当我应用uiview动画来扩大搜索栏的范围时,它会立即弹出到最终结果,好像该对象在内部控制它的动画效果并且不允许我顺利地应用我自己的动画。
如果我为位置设置动画,它会平滑移动,但我怀疑文本输入根据取消按钮的存在进行调整这一事实可能意味着我们没有公共访问权限通过UIView动画设置宽度动画。下面的示例代码段将条形图从x = 0滑动到100,但将宽度弹出为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){
}];
答案 0 :(得分:28)
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];
}];
希望这有帮助。
答案 1 :(得分:15)
仅供参考,您可以使用UIViewAnimationOption
代替明确调用layoutsubviews
,
所以代码看起来像这样..
[UIView animateWithDuration:0.5
delay:0
options:UIViewAnimationOptionLayoutSubviews
animations:^{
//Set the frame you want to the search bar
}
completion:^(BOOL finished) {
}];
答案 2 :(得分:0)
(当用户开始/结束编辑时,此代码会放大/缩小左侧的searchBar 93 像素)
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)
}
}