新浪微博之自定义搜索框

来源:互联网 发布:sql 查询重复记录 编辑:程序博客网 时间:2024/05/17 08:28

搜索框继承于UITextField

@interface WZSearchBar : UITextField


@end


注意:一个拉伸不变形的问题。

+(instancetype)resizeableImageWithName:(NSString *)imageName

{

    UIImage *image = [UIImageimageWithName:imageName];

    CGFloat left = image.size.width *0.5;

    CGFloat top = image.size.height *0.5;

//实现拉伸不变形

    image = [imagestretchableImageWithLeftCapWidth:lefttopCapHeight:top];

    return image;

}


@implementation WZSearchBar


- (instancetype)initWithFrame:(CGRect)frame

{

    self = [superinitWithFrame:frame];

    if (self)

    {

        //设置背景图片

        self.background = [UIImageresizeableImageWithName:@"searchbar_textfield_background"];

        //设置文本垂直居中

        self.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;

        //设置清除按钮

        self.clearButtonMode =UITextFieldViewModeWhileEditing;

        

        //添加放大镜到搜索框上

        UIImageView *iv = [[UIImageViewalloc] initWithImage:[UIImageimageWithName:@"searchbar_textfield_search_icon"]];

        self.leftView = iv;

        self.leftViewMode =UITextFieldViewModeAlways;

        

        CGRect frame = iv.frame;

        frame.size.width =40;

        iv.frame = frame;

        iv.contentMode =UIViewContentModeCenter;

        

        //设置默认提示问题

        self.placeholder =@"亲,请输入要搜索的内容~";

        self.frame =CGRectMake(0,0, 300,35);

    }

    returnself;

}


@end

另外要注意的一个问题:

WZSearchBar *searchBar = [[WZSearchBaralloc] init];

    searchBar.placeholder =@"~请输入要搜索的内容~";

    //注意:如果控件是添加到导航条上作为导航条的titleView,设置Framex,y无效

    searchBar.frame =CGRectMake(0,0, 300,35);

    self.navigationItem.titleView = searchBar;



0 0
原创粉丝点击