UITextField通过UIPickerView显示选择内容

好长时间不用,很多技能恢复了初始化状态,今天简单的复习了一下UIPickerView,进行了如下总结,希望可以帮到初学者:

  • 使用步骤:

    1. 初始化textField并设置代理
    2. 在代理方法 textFieldDidBeginEditing: 中初始化UIPickerView
    3. 通过触发按钮隐藏UIPickerView,并将UIPickerView选择后内容赋给textField.text
  • 代码
    (1)初始化

- (void)viewDidLoad {
    [super viewDidLoad];

    self.sexTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 80, 100, 40)];
    self.sexTF.delegate = self;
    self.sexTF.borderStyle = UITextBorderStyleLine;
    self.sexTF.textColor = [UIColor blackColor];
    self.sexTF.textAlignment = NSTextAlignmentLeft;
    self.sexTF.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.sexTF];

    _sexArr = @[@"性别:男",@"性别:女"];

}

(2) 实现UITextFieldDelegate

#pragma - mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //隐藏键盘,避免遮挡pickerView
    [self.sexTF resignFirstResponder];
    [self showSexPickerView];

}

(3)初始化PickerView,并实现pickerView相关代理

- (void)showSexPickerView{

    //控制pickerView隐藏按钮
    UIButton *donePickerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    donePickerBtn.frame = CGRectMake((self.view.frame.size.width-100)/2.0, self.view.frame.size.height - 50, 100, 40);
    donePickerBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [donePickerBtn setTitle:@"确定" forState:UIControlStateNormal];
    [donePickerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [donePickerBtn addTarget:self action:@selector(hideSexPickerView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:donePickerBtn];

    //pickerView
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 200)];
    self.pickerView.showsSelectionIndicator=YES;
    self.pickerView.delegate=self;
    self.pickerView.dataSource=self;
    self.pickerView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
    self.pickerView.showsSelectionIndicator = YES;
    [self.view addSubview:self.pickerView];
}

#pragma - mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    return _sexArr[row];
}

#pragma - mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{

    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _sexArr.count;
}

(4)隐藏pickerView并将选中内容赋值给textField

- (void)hideSexPickerView{

    NSInteger row = [self.pickerView selectedRowInComponent:0];
    self.sexTF.text = [_sexArr objectAtIndex:row];
    [self.pickerView removeFromSuperview];

}

实现结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值