最简单的搜索,Search

       之前一直为搜索而烦恼,有时候用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;
}

   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值