IOS性别

#pragma mark - 性别
- (void)initSex {
    UIPickerView *picker = [[[UIPickerView alloc] init] autorelease];
    // 设置数据源
    picker.dataSource = self;
    // 设置代理
    picker.delegate = self;
    // 明显地显示选中了哪一行
    picker.showsSelectionIndicator = YES;
    
    self.sex.inputView = picker;
   
}

// reusingView:(UIView *)view就是缓存池中的可循环利用的View
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    static int iconTag = 10;
    static int labelTag = 20;
    
    // 如果没有可循环利用的View
    if (view == nil) {
        view = [[[UIView alloc] init] autorelease];
        CGFloat viewHeight = 50;
        view.bounds = CGRectMake(0, 0, 100, viewHeight);
        
        // 添加ImageView
        UIImageView *icon = [[[UIImageView alloc] init] autorelease];
        CGFloat iconX = 5;
        CGFloat iconWidth = 32;
        CGFloat iconHeight = 32;
        CGFloat iconY = (viewHeight - iconHeight) * 0.5f;
        icon.frame = CGRectMake(iconX, iconY, iconWidth, iconHeight);
        icon.tag = iconTag;
        [view addSubview:icon];
        
        // 添加文本
        UILabel *label = [[[UILabel alloc] init] autorelease];
        label.frame = CGRectMake(iconX + iconWidth + 15, 0, 60, viewHeight);
        label.backgroundColor = [UIColor clearColor];
        label.tag = labelTag;
        [view addSubview:label];
    }


#pragma mark 监听选中了某一行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.sex.text = row==0?@"男":@"女";
}

#pragma mark 返回NO代表不允许手动改变文本框的文本
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 只有生日和性别才不允许修改文字
    return !(textField == self.birthday || textField == self.sex);
 
 
原文地址:https://www.cnblogs.com/wangshengl9263/p/3050395.html