1

as the topic already says, i try to create a small line on top of my UIKeyboard appearance. The reason is, if i pop up the white keyboard while having a white background, it looks just awful.

One idea would be to create a thin 1px line and place it on the bottom, hide it and show it whenever there is the keyboard displayed and align it with auto layout. The disadvantage of this idea is to do it in every view.

Thanks for your ideas.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Fry
  • 922
  • 2
  • 10
  • 24

3 Answers3

6

Every UITextField and UITextView has an inputAccessoryView property (inherited from the UIResponder superclass). When one of these views becomes first responder and the system presents the on-screen keyboard, the system automatically displays the inputAccessoryView of the first responder along the top of the keyboard. For example, in this answer, the dark bar with the left and right arrows and the “Done” button is an inputAccessoryView.

So the easiest way for you to get a thin line on top of the keyboard is probably to create a one-point tall view and set it as the inputAccessoryView of your text field or text view. Set the background color of the accessory view to a dark color.

Community
  • 1
  • 1
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Yep, thats the right thing, os i accept your answer, i just add some code for people to make it easier to follow up. – Fry Jul 10 '16 at 21:22
5

Easiest way to do this to add an inpustAccessoryView for textFiled when it becomes first responder and the system presents the on-screen keyboard.

Try this out: Swift 3:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {   

        let separatorView = UIView(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1))
        separatorView.backgroundColor = UIColor.lightGray
        textField.inputAccessoryView = separatorView

    return true
}
Tushar Korde
  • 1,189
  • 12
  • 23
2

So as Rob already wrote, the AccessoryView is the correct and smoothest solution, because Apple solves all animations, displaying and so on, in a correct way so no worry to take care about anything else.

I solved it as an extension. I wanted it to display a small devider on the bottom so i have a closed Numeric keyboard:

Swift 2.0:

extension UITextField {

override public func becomeFirstResponder() -> Bool {
    self.addSeparatorInputAccessoryIfNumericKeyboardOnPhone()
    return super.becomeFirstResponder()
}

func addSeparatorInputAccessoryIfNumericKeyboardOnPhone() {
    guard self.keyboardType == .NumberPad else {
        return
    }

    guard UIDevice.currentDevice().userInterfaceIdiom == .Phone else {
        return
    }

    let view = UIView(frame: CGRectMake(0, 0, 0, 1 / UIScreen.mainScreen().scale))
    view.backgroundColor = UIColor.lightGrayColor()
    self.inputAccessoryView = view
}

}

Fry
  • 922
  • 2
  • 10
  • 24