iOS 实现TextField的picker效果

只是简单的实现TextField的picker效果
可扩展:
1 . pickerView换成TableView、DataPickerView或者其他自定义的View
2 . 自定义Button, 把这个TextField添加到上面
3 . 对于iPad有PopViewController
4 . 等。。。

iOS 实现TextField的picker效果_第1张图片
picker.png
#define WID [UIScreen mainScreen].bounds.size.width
- (void)initUI{
    self.placeholder = @"请选择城市";
    self.clearButtonMode = UITextFieldViewModeNever;
    self.delegate = self;
    _idx = -1;
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WID, 216)];
    contentView.backgroundColor = [UIColor whiteColor];
    // toolbar
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, WID, 30)];
    UIBarButtonItem *flexibleItem1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *flexibleItem2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:@"请选择" style:UIBarButtonItemStylePlain target:self action:nil];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"X" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    toolBar.items = @[flexibleItem1,item1,flexibleItem2,item2];
    [contentView addSubview:toolBar];
    // picker
    _pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 30, WID, 186)];
    _pickView.showsSelectionIndicator = YES;
    _pickView.delegate = self;
    _pickView.dataSource = self;
    [contentView addSubview:_pickView];
    
    self.inputView = contentView;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 10;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return self.cityNames[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    [self resignFirstResponder];
    _idx = row;
    self.text = self.cityNames[row];
}

// select 记住的选项
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (_idx >=0 && _idx < self.cityNames.count) {
        [_pickView selectRow:_idx inComponent:0 animated:YES];
    }
    return YES;
}

// picker 的title赋值
- (void)reloadData:(NSArray *)dataArray{
    _cityNames = [dataArray copy];
    [_pickView reloadAllComponents];
}

// 取消文本框粘贴功能
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    return NO;
}

- (void)dismiss{
  [self resignFirstResponder];
}

你可能感兴趣的:(iOS 实现TextField的picker效果)