这在 Objective-C 中对我有用。看起来你有足够的能力把它翻译成 Swift:
[[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”是您在代码中绘制的图像,该图像返回与 UISearchBar 矩形大小相同的 UIImage。您可以找到方法来绘制您想要的背景颜色的图像,然后将图像的角变圆。这也是在 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 和一种 meme 语言,直到真正的编码人员使它不是 meme 语言,所以坚持使用 Objective-C)。
祝你好运
编辑
如果您使用布局约束,请确保您设置了约束,如果您不使用约束,则删除
[self.searchBar setTranslatesAutoresizingMaskIntoConstraints:false];
然后设置 UISearchBar 的框架