之前一直为搜索而烦恼,有时候用UITextField 做搜索框,代码是这样写,有时候用UISearchController 代码又是那样写,而且,这两种写的搜索框,对于初学者,跳来跳去比较繁琐,几下就弄晕了。
swift 2.0有一个filter 属性,按这个属性写了一个简单的搜索代码,不用跳转控制器,相信即使是初学者,一样也能看懂,话不多说,直接上代码。。。。。
swift 版:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView! {
didSet {
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
}
var searchTextField : UITextField!
let array = ["Iphone","Sum","BlueBerry","Motol","Nokia","Huawei","Mi"]
var searchArray = []
override func viewDidLoad() {
super.viewDidLoad()
searchTextField = UITextField(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width - 40, height: 60))
searchTextField.placeholder = "search"
searchTextField.addTarget(self, action: "textFieldEditChanged:", forControlEvents: .EditingChanged)
navigationItem.titleView = searchTextField
tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
func textFieldEditChanged(textField: UITextField) {
let selectRange = textField.markedTextRange
if selectRange == nil {
searchData()
}
}
func searchData() {
let searchText = (searchTextField.text ?? "").stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if !searchText.isEmpty {
searchArray = array.filter({ (file) -> Bool in
if file.rangeOfString(searchText) != nil {
return true
}
return false
})
}
tableView.reloadData()
}
//MARK: - UITableViewDelegate, UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let text = (searchTextField.text ?? "") as NSString
if text.length > 0 {
return searchArray.count
}
return array.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let text = (searchTextField.text ?? "") as NSString
if text.length > 0 {
cell.textLabel?.text = searchArray[indexPath.row] as? String
return cell
}
cell.textLabel?.text = array[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let text = (searchTextField.text ?? "") as NSString
if text.length > 0 {
print("\(searchArray[indexPath.row])")
} else {
print("\(array[indexPath.row])")
}
}
}
OC 版:
#import "ViewController.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(strong, nonatomic) UITableView *tableView;
@property(strong, nonatomic) UITextField *searchTextField;
@property(strong, nonatomic) NSMutableArray *searchArray;
@property(strong, nonatomic) NSArray *array;
@end
@implementation ViewController
-(NSMutableArray *)searchArray {
if (_searchArray == nil) {
_searchArray = [NSMutableArray array];
}
return _searchArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.array = @[@"Iphone",@"Sum",@"BlueBerry",@"Motol",@"Nokia",@"Huawei",@"Mi"];
self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
self.searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 40, 50)];
self.searchTextField.placeholder = @"屌丝们,尽情的搜吧。。。";
[self.searchTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
self.navigationItem.titleView = self.searchTextField;
}
-(void)textFieldChange:(UITextField *)sender {
UITextRange *range = [sender markedTextRange];
if (range == nil) {
[self searchData];
}
}
-(void)searchData {
NSString *searchText = self.searchTextField.text;
[self.searchArray removeAllObjects];
if (![searchText isEqualToString:@""]) {
for (NSString* text in self.array) {
NSRange range = [text rangeOfString:searchText];
if (range.length > 0) {
[self.searchArray addObject:text];
}
}
}
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *text = self.searchTextField.text;
if (text.length > 0) {
return self.searchArray.count;;
}
return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
NSString *text = self.searchTextField.text;
if (text.length > 0) {
cell.textLabel.text = self.searchArray[indexPath.row];
return cell;
}
cell.textLabel.text = self.array[indexPath.row];
return cell;
}