iOS自定義搜索框


如果只是在某個地方添加一個自定義的搜索框,只需要添加以下代碼:

//創建搜索框對象

UITextField *searchBar=[[UITextField alloc] init];

searchBar.width=300;

searchBar.height=30;

searchBar.font=[UIFont systemFontofSize:15];

searchBar.placeholder=@"請輸入搜索框";

searchBar.backgroud=[UIImage imageNamed:@"searchBar_backgoud"];

//創建搜索框內的左側搜索標志

UIImageView *searchImage=[[UIImage alloc]init];

searchImage.image=[UIImage imageNamed:@"searchBar_image"];

searchImage.width=30;    //需要給大小,否則顯示不出來

searchImage.height=30;

searchImage.contentMode=UIViewContentModeCenter;  //居中

//把標志放到搜索框內

searchBar.leftVIew=searchImage;

searchBar.leftViewMode=UITextFieldViewModeAlways; //標志一直會存在

[self.view addSubview:searchBar]

 

對於這種自定義的東西都進行封裝,因為以后用到的時候不需要大量的粘貼、復制,只需要

導入頭文件就可以

過程:

新建一個類SearchBar繼承自UITextField

在.h文件中定義一個方法,在.m文件中實現

-  (id)initWithFrame:(CGRect)frame

{

      self=[super initWithFrame:frame];

      if(self){

        self.font=[UIFont systemFontofSize:15];

        self.placeholder=@"請輸入搜索框";

        self.backgroud=[UIImage imageNamed:@"searchBar_backgoud"];

         //創建搜索框內的左側搜索標志

        UIImageView *searchImage=[[UIImage alloc]init];

        searchImage.image=[UIImage imageNamed:@"searchBar_image"];

        searchImage.width=30;    //需要給大小,否則顯示不出來

        searchImage.height=30;

        searchImage.contentMode=UIViewContentModeCenter;  //居中

        //把標志放到搜索框內

        self.leftVIew=searchImage;

        self.leftViewMode=UITextFieldViewModeAlways; 

}

return self;

}

+(instancetype)SearchBar

{

      return [[self alloc] init];

} 

 

在想添加搜索框的地方導入這個類

SearchBar *searchbar=[[UITextField alloc]init];

searchbar.width=300;

searchbar.height=30;

[self.view addSubview:searchbar];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM