【问题标题】:Move button with Keyboard, Swift带键盘的移动按钮,Swift
【发布时间】:2020-03-20 15:44:48
【问题描述】:
@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        if self.textView.frame.origin.y == 0 {
            let height = keyboardSize.height
            self.textButton.frame.origin.y -= height
            Log.debug("height: \(height)")
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
     if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

    if self.textButton.frame.origin.y != 0 {
        let height = keyboardSize.height
        self.textButton.frame.origin.y += height
        Log.debug("height: \(height)")
    }
}
}

我用适当的观察者调用了这 2 个函数。 问题是第二次键盘显示后键盘的高度发生了变化。这就是发生的事情=>

  • 键盘显示 => 高度 346
  • 键盘隐藏 => 高度 346
  • 键盘显示 => 高度 243
  • 键盘隐藏 => 高度 346
  • 键盘显示 => 高度 243

这是我设置按钮的地方:

textButton.frame = CGRect(x: textView.frame.width - 95, y: textView.frame.height , width: 70, height: 70)

这是我从 ViewDidLoad() 调用的按钮函数

 @objc func crossButtonTapped(_ sender:UIButton) {
    self.textView.resignFirstResponder()
}

附:如果我希望键盘在单击按钮时显示并在第二个按钮单击时隐藏怎么办?

谢谢!

【问题讨论】:

    标签: swift user-interface uiviewcontroller keyboard uibutton


    【解决方案1】:

    首先,如果您想添加会粘在键盘上方的按钮,我建议使用“UIToolbar”。

    关于你的 P.S 很简单:

    @objc func crossButtonTapped(_ sender:UIButton) {
        self.textView.isFirstResponder ? self.textView.resignFirstResponder() : 
        self.textView.becomeFirstResponder() 
    }
    

    希望对你有帮助:)

    【讨论】:

    • 感谢您的 P.S. !!感谢您对 UIToolbar 的建议,但我觉得键盘的行为很奇怪……我想按原样修复它。我的意思是为什么键盘在第二次点击时会失去 -103height
    • 尝试将“keyboardFrameBeginUserInfoKey”更改为“keyboardFrameEndUserInfoKey”我认为它应该可以解决问题
    • 你是我的英雄
    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2017-01-08
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多