Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display UIView over keyboard in iOS

I want to create a simple view over keyboard, when users tap "Attach" button in inputAccessoryView. Something like this:

enter image description here

Is there an easy way to do it? Or i should create my custom keyboard?

like image 595
pavel_s Avatar asked Sep 04 '15 06:09

pavel_s


People also ask

How do I move the view up on keyboard in IOS?

The best way to do this is to place your content inside a UIScrollView, then adjust the scroll view's contentInset property by the height of the keyboard when it's shown. Absolutely do not assume the keyboard height--use the value from the "keyboard will show" notification.

What is a UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.


2 Answers

Swift 4 version:

let customView = UIView(frame: CGRect(x: 0, y: self.view.frame.size.height - 300, width: self.view.frame.size.width, height: 300))
customView.backgroundColor = UIColor.red
customView.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
UIApplication.shared.windows.last?.addSubview(customView)

The trick is to add the customView as a top subview to the UIWindow that holds the keyboard - and it happens to be the last window in UIApplication.shared.windows.

like image 74
Milan Nosáľ Avatar answered Sep 30 '22 15:09

Milan Nosáľ


As Tamás Sengel said, Apple's guidelines does not support adding a view over the keyboard. The recommended way to add a view over keyboard in Swift 4 & 5 is:

1) Add view with your "Next" button in your storyboard as external view and connect in your class (see Explain Image), in my case:

IBOutlet private weak var toolBar: UIView!

2) For the textfield you want to add your custom view over keyboard, add it as accessory view in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    phoneNumberTextField.inputAccessoryView = toolBar
}

3) Add action for "Next" button:

@IBAction func nextButtonPressed(_ sender: Any) {
    descriptionTextView.becomeFirstResponder()

    // or -> phoneNumberTextField.resignFirstResponder()
}

Explain Image: enter image description here

Method 2: Result with image

enter image description here

In TableView Controller - add stricked view at bottom

Please follow this great link to handle safe area for screens like iPhone X if you want to use this method(2). Article: InputAccessoryView and iPhone X

override var inputAccessoryView: UIView? {
    return toolBar
}

override var canBecomeFirstResponder: Bool {
    return true
}
like image 23
Egzon P. Avatar answered Sep 30 '22 14:09

Egzon P.