Angel Caro
Angel Caro

Reputation: 93

How to disable keyboard on specific textField but allow picker view as input Swift?

I have 2 textFields in a view controller one uses a pickerView as input and the other uses a keyboard, the problem is the keyboard is still enabled under the pickerView. I have it set up that when the textfield in the bottom is being used the keyboard moves the view up to make the textField visible but when i click on the top textField which uses the pickerView it also moves the view up and you can't see the input on that textField. I need to only use the pickerView on top textField so the view won't move up when that textfield is being used. Here is what i'm using to move view up:

func keyboardWillShow(notification: NSNotification) {

    bottomConstraint.constant = 200
    topConstraint.constant = -200
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}



func keyboardWillHide(notification: NSNotification) {

    bottomConstraint.constant = 8
    topConstraint.constant = 10
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

Here is my setup for the pickerView in viewDidLoad: (colorCodePicker is the textField with pickerView as input)

let pickerView = UIPickerView()

    pickerView.delegate = self

    pickerView.backgroundColor = UIColor.whiteColor()

    colorCodePicker.inputView = pickerView

I have tried most of the solutions here but haven't got any to work i.e. if i disable user input than i can't call the pickerView, also tried inserting a clear button over the textField like one of the suggestions with no luck. Or maybe a solution to only move view up when bottom textField is active, any ideas?

Upvotes: 2

Views: 1945

Answers (3)

Mert Buran
Mert Buran

Reputation: 3017

There can be quick fixes to save the day but I'd suggest using UITableViewController for building form pages. It automatically does keyboard handling. Yes, you need to create UITableViewCells which contain UITextFields but I think this is feasible.

I do not like using stand-alone UITableViewController since they do not have a UIView as their self.view, therefore I embed them to my view controller and access its tableView during segue. Even if it is not dataSource/delegate of its tableView, it handles keyboard.

Upvotes: 1

zc246
zc246

Reputation: 1514

In both keyboardWillShow and keyboardWillHide check if colorCodePicker.isFirstResponder() to decide whether to change the constraint.

Upvotes: 1

kekkeme
kekkeme

Reputation: 942

I know it won't be exact answer but if you just use IQKeyboardManager you do not need to think about those staff in any scene of your application.

IQKeyboardManager

Upvotes: 1

Related Questions