Boy Channarong
Boy Channarong

Reputation: 31

How to I add preview text on top of keyboard layout in iOS

I want to show preview text on top of keyboard like this:

How do I solve with this problem?

Upvotes: 2

Views: 998

Answers (2)

Mohammadalijf
Mohammadalijf

Reputation: 1377

@dahiya_boy's method is much better i guess. but if you need alternative way...

you can observe on this notifications and show or hide a label that show a preview of text.

 // this one trigger keyboardWillShow when keyboard is shown to user
 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

 // this one trigger keyboardWillHide when keyboard is dismissing
 NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

and in function keyboardWillShow you can display a label for preview on top of the keyboard.

func keyboardWillShow(sender: NSNotification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
                // keyboard height is available you can use it to put image in view
            }
        }
}




func keyboardWillHide(sender: NSNotification) {
    // you can hide the label here
}

Upvotes: 0

dahiya_boy
dahiya_boy

Reputation: 9503

I think this is what you want :

enter image description here

Code :

override func viewDidAppear(_ animated: Bool) {
        let viewAcc = UIView()
        viewAcc.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)
        viewAcc.backgroundColor = UIColor.gray

        let newTF = UITextField(frame: CGRect(x: 2, y: 10, width: self.view.frame.size.width - 75 , height: 30))
        newTF.backgroundColor = UIColor.white
        newTF.borderStyle = UITextBorderStyle.none

        let btnDone = UIButton(frame: CGRect(x: newTF.frame.size.width + 10, y: 5, width: 45, height: 30 ))
        btnDone.backgroundColor = UIColor.blue
        btnDone.setTitle("Done", for: .normal)

        viewAcc.addSubview(newTF)
        viewAcc.addSubview(btnDone)
        self.mytextField.inputAccessoryView = viewAcc
    }

Reference:

Apple Doc Reference

Upvotes: 2

Related Questions