如何实现iOS软件盘有时候顶起有时候不顶

1. 流程

下面是实现iOS软件盘有时候顶起有时候不顶的步骤:

步骤 操作
1 监听软键盘弹出和收起的通知
2 根据软键盘弹出和收起的通知调整界面布局

2. 具体操作步骤

步骤1:监听软键盘弹出和收起的通知

在需要调整布局的ViewController中添加以下代码:

// 监听键盘弹出和收起的通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

viewWillDisappear方法中移除通知的监听:

// 移除通知监听
NotificationCenter.default.removeObserver(self)

步骤2:根据软键盘弹出和收起的通知调整界面布局

在ViewController中添加以下方法来实现键盘弹出时的布局调整:

@objc func keyboardWillShow(_ notification: Notification) {
    // 获取键盘高度
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        // 调整界面布局,比如将输入框上移
        // 代码实现...
    }
}

@objc func keyboardWillHide(_ notification: Notification) {
    // 键盘收起时恢复原始布局
    // 代码实现...
}

3. 类图

classDiagram
    class ViewController {
        + keyboardWillShow(notification: Notification)
        + keyboardWillHide(notification: Notification)
    }

引用形式的描述信息

通过上述步骤,你可以实现iOS软件盘有时候顶起有时候不顶的效果。记得在适当的时候添加和移除通知的监听,以避免出现内存泄漏的问题。希望这篇文章对你有所帮助,祝你在iOS开发的路上越走越远!