年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 3676|回复: 0

自定义UISearchBar 适配IOS6和IOS7

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-8-19 15:59:42 | 显示全部楼层 |阅读模式
    考虑到统一ios6与ios7的界面风格,UISearchBar通过重自定义来实现,重写一个类继承自UISearchBar
    1、效果图:
    QQ20140819-1@2x.png
    2、部分代码:
    附注释说明
    SASearchBar.h
    1. #import <UIKit/UIKit.h>
    2. @interface SASearchBar : UISearchBar
    3. @property (nonatomic, strong)   UITextField     *textField;
    4. @property (nonatomic, strong)   UIButton        *searchBtn;
    5. @end
    复制代码
    SASearchBar.m
    1. #import "SASearchBar.h"
    2. @implementation SASearchBar
    3. #pragma mark 初始化
    4. - (id)initWithFrame:(CGRect)frame
    5. {
    6.     if (self = [super initWithFrame:frame]) {
    7.         // 设置背景色为透明,这句在ios6中很重要!!
    8.         self.backgroundColor = [UIColor clearColor];
    9.         self.placeholder = @"搜索号码或姓名";
    10.     }
    11.     return self;
    12. }
    13. #pragma mark 调整子控件
    14. - (void)layoutSubviews
    15. {
    16.     [super layoutSubviews];
    17.    
    18.     UIView *baseView = iOS7 ? [self.subviews firstObject] : self;
    19.    
    20.     // 移除背景图片
    21.     [[baseView.subviews firstObject] removeFromSuperview];
    22.    
    23.     // 获取TextField
    24.     self.textField = [baseView.subviews firstObject];
    25.     self.textField.leftView = nil;
    26.     self.textField.background = nil;
    27.     self.textField.backgroundColor = [UIColor clearColor];
    28.     self.textField.frame = CGRectMake(0, 0, baseView.frame.size.width - 30, 44);
    29.    
    30.     // 创建搜索按钮
    31.     self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    32.     UIImage *searchIcn = [UIImage imageNamed:@"icon_invite_search_btn.png"];
    33.     [self.searchBtn setImage:searchIcn forState:UIControlStateNormal];
    34.     self.searchBtn.frame = CGRectMake(baseView.frame.size.width - 30, 10, 20, 20);
    35.     [baseView addSubview:self.searchBtn];
    36.    
    37.     NSLog(@"%@", self.subviews);
    38. }
    39. #pragma mark 绘制背景图片
    40. - (void)drawRect:(CGRect)rect
    41. {
    42.     UIImage *image = [UIImage resizeImage:@"textField_line_selected.png"];
    43.     [image drawInRect:CGRectMake(0, 0, rect.size.width, rect.size.height)];
    44. }
    45. @end
    复制代码
    3、素材下载: Resource.zip (18.54 KB, 下载次数: 4)
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-2 21:25 , Processed in 0.052518 second(s), 25 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表