for subView in searchBar.subviews {
if let scopeBar = subView as? UISegmentedControl {
scopeBar.backgroundColor = UIColor.blueColor()
}
}
我一直在尝试上面的代码尝试获取对scopeBar的引用,然后设置其背景颜色,但我无法获得引用。它似乎只经历了一次循环,暗示搜索栏只有一个子视图。在调试器中,搜索栏似乎有一个名为_scopeBar的实例变量,其类型为(UISegmentedControl *)。
if let topView = searchBar.subviews.first {
for subView in topView.subviews {
if let cancelButton = subView as? UIButton {
cancelButton.tintColor = UIColor.whiteColor()
cancelButton.enabled = true
}
}
}
第二个代码块用于访问搜索栏的cancelButton。
答案 0 :(得分:4)
您可以将scopeBar背景图像设置为纯色图像。
首先,您需要create an UIImage from a color。为此,您可以创建一个函数或extension on the UIImage,例如以下代码:
Swift 3
import UIKit
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
之后,您只需在范围栏上设置backgroundImage:
Swift 3
// Set the scopeBar's background color:
searchBar.scopeBarBackgroundImage = UIImage.imageWithColor(color: UIColor.blue)
答案 1 :(得分:0)
我有一个示例问题,我解决了以下代码。
CGSize imageSize = CGSizeMake(64, 64);
UIColor *fillColor = [UIColor colorWithRed:228/255.0 green:228/255.0 blue:228/255.0 alpha:1.0];
UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
[fillColor setFill];
CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.searchController.searchBar.scopeBarBackgroundImage = image;
答案 2 :(得分:-1)
- (void)changeScopeBarColor {
NSMutableArray<UIView*> *views = [NSMutableArray new];
NSArray<UIView *> *subviews = [_searchBar subviews];
[views addObjectsFromArray:subviews];
for (;;) {
if (views.count == 0) {
break;
}
UIView *v = [views firstObject];
[views removeObject:v];
if ([[[v class] description] isEqualToString:@"_UISearchBarScopeBarBackground"]) {
v.backgroundColor = [UIColor whiteColor];
break;
}
if (v.subviews.count > 0)
[views addObjectsFromArray:v.subviews];
}
}