自动弹出pickerview

  UIPickerView是开发中经常使用的控件,日期选择、年龄选择、城市的多级联动等等都会使用,它通常是在点击某个按钮后出现,展示方式和UITextView同样,从页面底部弹出,选中后或者点击控件之外区域自动缩回。git

      系统原生的picker view是不支持自动弹出收回的,因此咱们要对它进行一下改造。github

      思路:为了模仿键盘的弹出收回效果,咱们设置一个UITextView,点击它就能吊起键盘。UITextView有一个inputview,咱们只要将其替换成本身须要的picker view便可。ide

  效果图
spa

 

        主要代码:新建一个View继承与UIView,定义两个视图textView合pickerView。而后建立他们,以下:3d

- (void)createContentView {
    self.textView = [[EXNoPasteTextField alloc] initWithFrame:self.bounds];
    self.textView.font = self.textFont;
    self.textView.autocorrectionType = UITextAutocorrectionTypeNo;
    [self addSubview:self.textView];
    
    _pickerView = [[UIPickerView alloc] init];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    self.textView.inputView = _pickerView;
    
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
    toolBar.barStyle = UIBarStyleDefault;
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTouched:)];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelTouched:)];
    
    // the middle button is to make the Done button align to right
    [toolBar setItems:[NSArray arrayWithObjects:cancelButton, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], doneButton, nil]];
    self.textView.inputAccessoryView = toolBar;
}
View Code

       手机端是彻底没问题的,iPad端会展现联想和复制按钮,须要自定义一个继承UITextView的TextView,屏蔽其粘贴功能。code

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    UIMenuController *menu = [UIMenuController sharedMenuController];
    if (menu) {
        menu.menuVisible = NO;
    }
    
    return NO;
}
View Code

  

       须要源码的,能够去个人GitHub:https://github.com/zhanghua0926/EXPickerTextVieworm

相关文章
相关标签/搜索