Objective C implementing a UIPickerView with a “Done” button

后端 未结 7 692
一向
一向 2020-12-03 08:56

I am trying to implement a \"Done\" button in a UIPickerView Similar to the one under this link

I looked in the class reference but I couldn t find it

Thank

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 09:22

    In case you are working on a Table View Cell and you are not using a UITextField (hence you won't be using the Accessory View), here's what I did:

    I created a table view cell called GWDatePickerCell that looks like this (no .nib files involved).

    GWDatePickerCell.h:

    #import 
    
    @interface GWDatePickerCell : UITableViewCell
    
    @property (nonatomic, strong) UIDatePicker *datePicker;
    @property (nonatomic, strong) UIToolbar *toolbar;
    @property (nonatomic, strong) UIBarButtonItem *buttonDone;
    
    @end
    

    GWDatePickerCell.m:

        #import "GWDatePickerCell.h"
    
        @implementation GWDatePickerCell
    
        - (id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
            if(!(self=[super initWithStyle:style reuseIdentifier:reuseIdentifier])) return nil;
    
        _datePicker = [[UIDatePicker alloc] init];
        [_datePicker setMinuteInterval:5];
        [_datePicker setDatePickerMode:UIDatePickerModeDateAndTime];
        [self.contentView addSubview:_datePicker];
    
        _toolbar = [[UIToolbar alloc] init];
        _buttonDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:nil action:nil];
        _toolbar.items = @[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], _buttonDone];
        [self.contentView addSubview:_toolbar];
    
        return self;
    }
    
    - (void)layoutSubviews{
        [super layoutSubviews];
        CGRect r = self.contentView.bounds;
        r.origin.y +=44;
        r.size.height = 216;
        CGRect tb = self.contentView.bounds;
        tb.size.height = 44;
        _datePicker.frame = r;
        _toolbar.frame = tb;
    }
    
    @end
    

    Now all I had to do when creating the cells in the Table View:

    • Specify the @selector for the Done button.
    • Set the correct cell height in heightForRowAtIndexPath

提交回复
热议问题