我的问题:我有一个使用UINavigationController
的用户入门过程,以介绍入门过程中的每个步骤。当推入其中带有UISearchBar
的视图控制器时,UISearchBar
会动画到位。
我的问题是什么: https://youtu.be/TKPLeJ9FmI4(问题发生在0:27,0:32,0:41周围)
我收集的内容:这似乎是在堆栈中的前一个视图控制器在推送下一个视图控制器之前执行异步功能时发生的,并且大概直到之后才完成异步功能。 UISearchBar
已经设置好动画。
我尝试过的事情:我尝试了对UISearchBar
进行子类化,并确保layoutSubviews
没有通过UIView.performWithoutAnimation
进行动画处理:
import UIKit
class SearchBar: UISearchBar {
override func layoutSubviews() {
UIView.performWithoutAnimation {
super.layoutSubviews()
}
}
}
类似地,我尝试在布置子视图时确保UISearchBar
的超级视图没有动画:
class MyViewController: UIViewController {
@IBOutlet var searchBar: UISearchBar!
override func viewDidLayoutSubviews() {
UIView.performWithoutAnimation {
super.viewDidLayoutSubviews()
}
}
}
我想知道的是:由于很难确定动画的确切原因,我很好奇是否有一种方法可以完全阻止UISearchBar
进行动画制作。我永远不会真正需要动画UISearchBar
。
[[UISearchBar appearance] setBackgroundImage:[UIImage new]
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
[[UISearchBar appearance] setBackgroundImage:[UIImage new]
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefaultPrompt];
[self.searchBar setSearchFieldBackgroundImage:finalImage forState:UIControlStateNormal];
[“ finalImage”是您在代码中绘制的图像,该图像返回的UIImage与UISearchBar的矩形大小相同。您可以找到绘制所需背景颜色的图像,然后将图像圆角化的方法。它也在Objective-C中。
- (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect {
UIGraphicsBeginImageContext(imageRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, imageRect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius {
CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0);
rect.size = image.size;
UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect
cornerRadius:radius];
[path addClip];
[image drawInRect:rect];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
所以UISearchBar的完整声明是这样的:
self.searchBar = [UISearchBar new];
CGRect rect = CGRectMake(0.0, 0.0, 44, 35);
UIImage *colorImage = [self imageWithColor:[UIColor whiteColor] withSize:rect];
UIImage *finalImage = [self roundImage:colorImage withRadius:10.0];
[self.searchBar setSearchFieldBackgroundImage:finalImage forState:UIControlStateNormal];
[self.searchBar setTranslatesAutoresizingMaskIntoConstraints:false];
[self.view addSubview:self.searchBar];
这是我发现删除Apple添加的所有时髦动画并根据需要自定义背景的唯一方法。祝你好运(对于那些因为不在Swift中而对此不满意的人,应该知道Swift是Ruby 2.0和一种模因语言,直到真正的编码人员使其不成为模因语言为止,因此请坚持使用Objective-C)。
祝你好运编辑
[如果使用布局约束,请确保设置约束,如果不使用约束,请删除
[self.searchBar setTranslatesAutoresizingMaskIntoConstraints:false];
然后设置UISearchBar的框架