UINavagationBar,UISearchBar,UITo…

来源:互联网 发布:杭州行知小学校园网 编辑:程序博客网 时间:2024/05/29 02:10

UINavagationBar,UISearchBar,UIToolBar,UITabBar 自定义Background Image

这里运用了object-c里面的一个类别,大体意思就是在不知道苹果封装起来的API内容的情况下,在外部程序中覆盖其原来的函数。大体这个意思吧。程序代码: 在程序的任何一个 .m文件 后面加上下面代码即可 记住 要在 @end的后面加上。

UINavigationBar:
@implementation UINavigationBar (CustomImage2)  
-(void)drawRect:(CGRect)rect 
  
     UIImage *image = [UIImage imageNamed:@"bar.png"];   
    [image drawInRect:CGRectMake(0, 0,self.frame.size.width,self.frame.size.height)];   
  
@end
UIToolBar:
@implementation UIToolbar(CustomImage2)   
-(void)drawRect:(CGRect)rect 
  
UIImage *image = [UIImage imageNamed:@"bar.png"];   
    [image drawInRect:CGRectMake(0, 0,self.frame.size.width,self.frame.size.height)];   
  
@end
UITabBar:
@implementation UITabBar(CustomImage2)   
-(void)drawRect:(CGRect)rect 
      
UIImage *image = [UIImage imageNamed:@"bar.png"];   
    [image drawInRect:CGRectMake(0, 0,self.frame.size.width,self.frame.size.height)];   
  
@end
上面这三个的用法都是一样的,关键是SearchBarSearchBar的背景图片控制不是由SearchBar 本身 而是由 UISearchBarBack来控制的,因此无法直接用上面的代码,需要手动把SearchBar上面的两个View删除了才行。
在你的ViewDidLoad或者任何一个程序可以执行到的地方写下如下代码,当然,你的searchBar得创建之后才行
且看删除代码
[[_searchBar.subviews objectAtIndex:0]setHidden:YES];
    [[_searchBar.subviews objectAtIndex:0]removeFromSuperview];
    for (UIView *subview in_searchBar.subviews) 
   {
       if ([subviewisKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
       {
           [subviewremoveFromSuperview];
          break;
       }
    }
这个代码 配合上面的那个类别
   @implementation UISearchBar(CustomImage2)   
-(void)drawRect:(CGRect)rect 
      
    UIImage *image = [UIImage imageNamed:@"bar.png"];   
    [image drawInRect:CGRectMake(0, 0,self.frame.size.width,self.frame.size.height)];   
  
@end