自動彈出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

相關文章
相關標籤/搜索