如何在iOS中的键盘布局上添加预览文本

时间:2017-05-22 04:43:34

标签: ios swift keyboard-events

我想在键盘上显示预览文字,如下所示:

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

enter image description here

代码:

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
    }

<强>参考:

Apple Doc Reference

答案 1 :(得分:0)

@ dahiya_boy的方法我觉得好多了。但如果你需要替代方式......

您可以观察此通知并显示或隐藏显示文本预览的标签。

 // 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)

并在功能键盘中显示您可以在键盘顶部显示预览标签。

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
}