UISearchBar:清除背景颜色或设置背景图像 [英] UISearchBar: clear background color or set background image

查看:216
本文介绍了UISearchBar:清除背景颜色或设置背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置搜索栏的背景图像或清除背景,例如笔记应用程序?

How can set the background image, or clear the background, of a search bar, like the note application?

推荐答案

我想出了一个效果很好的解决方案。您必须覆盖UISearchBar,然后隐藏背景和分段控制图层。然后绘制背景。

I just came up with a solution that works really well. You have to override the UISearchBar and then hide both the Background and Segment Control layers. Then Draw the background.

@ .m

#import "UISearchBar.h" 
#import <QuartzCore/QuartzCore.h>

@implementation UISearchBar(CustomBackground)

- (id)init
    {
        for ( UIView * subview in self.subviews ) 
        {
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground") ] ) 
                subview.alpha = 0.0;  

            if ([subview isKindOfClass:NSClassFromString(@"UISegmentedControl") ] )
                subview.alpha = 0.0; 
        } 

        return self;
    }

+ (UIImage *) bgImagePortrait
    {
        static UIImage *image = nil;
        if (image == nil)
            image = [[UIImage imageNamed:@"UISearchBarBack.png"] retain ];

        return image;
    }

+ (UIImage *) bgImageLandscape
    {
        static UIImage *image = nil;
        if (image == nil)
            image = [[UIImage imageNamed:@"UISearchBarBack.png"] retain];

        return image;
    }

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)contenxt
    {
        if ([self isMemberOfClass:[UISearchBar class]] == NO)
            return; 

        UIImage * image = ( self.frame.size.width > 320 ) ? [UISearchBar bgImageLandscape ] : [UISearchBar bgImagePortrait ];  

        for ( UIView * subview in self.subviews ) {
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground") ] ) 
                subview.alpha = 0.0; 

            if ([subview isKindOfClass:NSClassFromString(@"UISegmentedControl") ] )
                subview.alpha = 0.0; 
        }

        CGContextTranslateCTM( contenxt , 0 , image.size.height );
        CGContextScaleCTM( contenxt, 1.0, -1.0 );
        CGContextDrawImage( contenxt , CGRectMake( 0 , 0 , image.size.width , image.size.height ), image.CGImage );
    }  

@end

@ .h

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>


@interface UISearchBar(CustomBackground) 

@end

希望这有帮助!

这篇关于UISearchBar:清除背景颜色或设置背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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