UISearchBar范围栏背景图片可设置,但不是它的颜色? [英] UISearchBar scope bar background image settable, but not its color?

查看:231
本文介绍了UISearchBar范围栏背景图片可设置,但不是它的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我一直在尝试上面的代码来尝试获取对scopeBar的引用并随后设置其背景颜色,但我无法获得引用。它似乎只经历了一次循环,暗示搜索栏只有一个子视图。在调试器中,搜索栏似乎有一个名为_scopeBar的实例变量,类型为(UISegmentedControl *)。

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

第二个代码块用于访问搜索栏的cancelButton。

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

推荐答案

您可以将scopeBar背景图像设置为纯色图像。

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

首先,您需要从颜色创建UIImage 。为此,您可以在UIImage上创建一个函数或扩展名,例如以下代码:

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

之后,您只需在范围栏上设置backgroundImage:

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)

这篇关于UISearchBar范围栏背景图片可设置,但不是它的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆