ios - 当 View 出现在屏幕上时,如何让键盘将 View 向上推? Xcode swift

标签 ios xcode swift text keyboard

<分区>

所以我有一个带有文本字段的 View ,但文本字段位于底部。当我单击键盘时,它会弹出并覆盖文本字段,这是我的问题。我想知道是否有可能在键盘出现时将 View 的其余部分向上推?

最佳答案

您可以注册您的 View Controller ,以便在键盘即将显示时收到通知,然后将您的 View 向上推。

class ViewController: UIViewController {

var keyboardAdjusted = false
var lastKeyboardOffset: CGFloat = 0.0

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification: NSNotification) {
    if keyboardAdjusted == false {
        lastKeyboardOffset = getKeyboardHeight(notification)
        view.frame.origin.y -= lastKeyboardOffset
        keyboardAdjusted = true
    }
}

func keyboardWillHide(notification: NSNotification) {
    if keyboardAdjusted == true {
        view.frame.origin.y += lastKeyboardOffset
        keyboardAdjusted = false
    }
}

func getKeyboardHeight(notification: NSNotification) -> CGFloat {
    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    return keyboardSize.CGRectValue().height
}

}

关于ios - 当 View 出现在屏幕上时,如何让键盘将 View 向上推? Xcode swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561977/

相关文章:

ios - 我的 NSUserDefaults 代码不起作用

swift - 如何使用 IBInspectable 在属性检查器中设置夜间模式和白天模式颜色?

ios - 从 Swift 4 中的后台线程调用并运行 Firebase 4 的 UI API

iphone - 程序收到信号: SIGKILL mean when profiling an app running on device and using the xcode profiler to detect leaks是什么意思

ios - 使用 AvAudioEngine 输出时的耳机音量问题

ios - 导航栏的右侧按钮丢失

ios - CGContextDrawImage 绘制大图像非常模糊

ios - didReceiveMessage :(XMPPMessage *)message Not Running Actual Device

iphone - 项目转换 - iPad 到 iPhone

ios - Swift 中的大型 Core Data 批量插入导致内存泄漏