Search code examples
xcodeswiftautolayoutuipickerview

Fitting UIPicker and 3 text fields on 3.5 and 4 inch devices


I have (from top to bottom) 2 UILabels, 1 UIPickerView, 3 UITexfield, and 1 button. Given the size of the picker, upon the keyboard appearing it overlaps my text fields on the 3.5 and 4 inch devices. I used some code to pop the text fields up when the keyboard shows, but I'm unsure what to do with the picker. I tried hiding it upon keyboard but it's too sudden and the user may want to change their choice which they can't easily. What should I do with the picker given the size limitations?

   override func viewDidLoad() {
        super.viewDidLoad()
        countyPicker.delegate = self
        countyPicker.dataSource = self


            NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
            NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
        }

        func keyboardWillShow(sender: NSNotification) {
            self.view.frame.origin.y -= 150
        }

        func keyboardWillHide(sender: NSNotification) {
            self.view.frame.origin.y += 150
  //          countyPicker.hidden = true

    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return titleData.mdCounties.count
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent componefnt: Int) {
 //       countyPicker.alpha = 0.3
        selectedCounty = titleData.mdCounties[row].name
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

        return titleData.mdCounties[row].name!
    }

Solution

  • Place the 1 UIPickerView and 3 UITexfield in a single view and pop up the entire view when the keyboard shows up.

    As you have already written the code to pop up the text fields it will work out.

    Hope this helps you. :)