Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar scope bar background image settable, but not its color?

    for subView in searchBar.subviews {
        if let scopeBar = subView as? UISegmentedControl {
            scopeBar.backgroundColor = UIColor.blueColor()
        }
    }

I've been trying the above code to attempt to get a reference to the scopeBar and subsequently set its background color, but I am not able to get a reference. It seems to only go through the loop once, implying that there is only a single subview for the search bar. In the debugger the search bar appears to have an instance variable called _scopeBar with a type of (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
            }
        }
    }

The second block of code works for accessing the cancelButton of the search bar.

like image 285
SwiftMatt Avatar asked Feb 08 '23 00:02

SwiftMatt


1 Answers

You can set the scopeBar background image as a solid color image.

First, you will need to create an UIImage from a color. In order to do that, you can create a function, or an extension on the UIImage, such as the following code:

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
    }
}

After that, you can simply set the backgroundImage on the scope bar:

Swift 3

// Set the scopeBar's background color:
searchBar.scopeBarBackgroundImage = UIImage.imageWithColor(color: UIColor.blue)
like image 178
Paulo Moreno Avatar answered Feb 10 '23 23:02

Paulo Moreno