2016-01-15 23 views
2
for subView in searchBar.subviews { 
     if let scopeBar = subView as? UISegmentedControl { 
      scopeBar.backgroundColor = UIColor.blueColor() 
     } 
    } 

我一直在嘗試上面的代碼,試圖獲得對scopeBar的引用,隨後設置其背景顏色,但我無法獲得參考。它似乎只經過一次循環,意味着搜索欄只有一個子視圖。在調試器中,搜索欄似乎有一個名爲_scopeBar的實例變量,其類型爲(UISegmentedControl *)。UISearchBar範圍欄可以設置背景圖片,但不是它的顏色?

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

您可以將scopeBar背景圖像設置爲純色圖像。您需要登錄create an UIImage from a color。爲了做到這一點,你可以創建一個功能,或者extension on the UIImage,如下面的代碼:

斯威夫特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範圍欄上:

斯威夫特3

// Set the scopeBar's background color: 
searchBar.scopeBarBackgroundImage = UIImage.imageWithColor(color: UIColor.blue) 
0
- (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]; 
    } 
} 
0

我有一個樣品的問題,我解決了這個爲b elow代碼。

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; 
相關問題