猫猫学iOS 之微博项目实战(5)微博自己定义搜索框searchBar

猫猫分享。必须精品

原创文章。欢迎转载。

转载请注明:翟乃玉的博客
地址:http://blog.csdn.net/u013357243

一:效果

用UITextField简单定义一个搜索框
这里写图片描写叙述

二:调用:

调用的代码。非常easy,直接init就能够,以后加功能自己加入即可了。

- (void)viewDidLoad {
    [super viewDidLoad];

    // 创建搜索框
    NYSearchBar *searchBar = [[NYSearchBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35)];
    searchBar.placeholder = @"猫猫搜索";


    // 设置titleView为搜索框
    self.navigationItem.titleView = searchBar;
}

三:代码:

NYSearchBar.m文件内容
NYSearchBar.h文件中面没有东西,
思路非常easy,就是左边放一个图片而已,能够自己加入其它东东。

//
//  NYSearchBar.m
//  猫猫微博
//
//  Created by apple on 15-7-29.
//  Copyright (c) 2015年 znycat. All rights reserved.
//

#import "NYSearchBar.h"

@implementation NYSearchBar


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {

        self.font = [UIFont systemFontOfSize:13];

        self.background = [UIImage imageWithStretchableName:@"searchbar_textfield_background"];

        // 设置左边的view
        // initWithImage:默认UIImageView的尺寸跟图片一样
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchbar_textfield_search_icon"]];

        // 为了空出左边一小块设置的
        imageV.width += 10;
        imageV.contentMode = UIViewContentModeCenter;
        self.leftView = imageV;
        // 一定要设置。想要显示搜索框左边的视图,一定要设置左边视图的模式
        self.leftViewMode = UITextFieldViewModeAlways;

    }
    return self;
}



@end

推荐一个iOS学习帅气的站点 : code4app

各种各样的iOS效果和源代码都用,随下随用。

原文地址:https://www.cnblogs.com/wzjhoutai/p/7278917.html