ios - UITextField不能随着键盘启动移动到正确的位置

标签 ios swift user-interface uiview uikeyboard

我试图使UITextField移动,使其位于键盘顶部(与iMessage相同),但无法弄清楚我的问题是什么。我已经审查了与此问题类似的问题,但到目前为止仍未成功。文本字段似乎略有移动,但最终位于键盘后面,因此希望这是一个愚蠢的坐标放置问题,有人可以向我指出。还要注意的另一件事是,下面的GIF在iPhone X上,但是,当我在iPhone 6上运行该应用程序时,UITextField会移到键盘上方的正确位置,但是在我键入任何内容后会立即移回其下方。任何帮助表示赞赏!

class ChatViewController: UIViewController {

@IBOutlet weak var messageView: UIView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var textMessageField: UITextField!
@IBOutlet weak var contactStatusLabel: UILabel!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var videoChatButton: UIButton!
let cellID = "cellID"
var contactIsOnline = false
var currentUser:G8User = G8User()
var currentContact:G8User = G8User()
var currentConversation : Conversation?
var videoToken = ""
var allMessages : [ChatMessage] = []
var onlineRef:DatabaseReference!
var incomingMessagesRef:DatabaseReference!


override func viewDidLoad() {
    super.viewDidLoad()
    sendButton.backgroundColor = UIColor(red: CGFloat(0/255), green: CGFloat(137.0/255.0), blue: CGFloat(249.0/255.0), alpha: 1)
    sendButton.layer.cornerRadius = 5
    videoChatButton.backgroundColor = UIColor.red
    videoChatButton.layer.cornerRadius = 5
    collectionView.alwaysBounceVertical = true
    collectionView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
    collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
    collectionView.register(ChatMessageCell.self, forCellWithReuseIdentifier: cellID)
    collectionView.dataSource = self
    collectionView.delegate = self

    // Used to dismiss keyboard
    let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
    tap.cancelsTouchesInView = false
    self.view.addGestureRecognizer(tap)



    // Set up keyboard observers
    NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)


}

 @objc func keyboardWillShow(notification: NSNotification) {
    print("SHOWING KEYBOARD")
     // TODO: Adjust scrolling for message view
     if let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue{

        let topOfMessageBox = keyboardFrame.origin.y - self.messageView.frame.height
         self.collectionView.frame = CGRect(x: collectionView.frame.origin.x,y: collectionView.frame.origin.y,width: collectionView.frame.width,height: topOfMessageBox - collectionView.frame.origin.y)
        self.messageView.frame = CGRect(x: messageView.frame.origin.x,y: topOfMessageBox,width: messageView.frame.width, height: messageView.frame.height)


     }
 }

 @objc func keyboardWillHide(notification: NSNotification) {
    print("HIDING KEYBOARD")

    self.collectionView.frame = CGRect(x: collectionView.frame.origin.x,y: collectionView.frame.origin.y,width: collectionView.frame.width,height:  messageView.frame.origin.y - collectionView.frame.origin.y )
    self.messageView.frame = CGRect(x: messageView.frame.origin.x,y: self.view.frame.maxY - messageView.frame.size.height,width: messageView.frame.width,height: messageView.frame.height)
 }

GIF of Issue

最佳答案

试试这个UIView扩展名,比如myTextField.bindToKeyboard()

extension UIView {

    func bindToKeyboard() {

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
    }

    @objc func keyboardWillChange(_ notification: NSNotification) {

        let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt
        let beginningFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let endFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        var deltaY = endFrame.origin.y - beginningFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        }, completion: nil)
    }
}

关于ios - UITextField不能随着键盘启动移动到正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59863919/

相关文章:

ios - 使用 Swift 在后端存储数据

user-interface - 调用 Sleep() 时用户界面变得无响应

iOS 应用程序加载器 - 应上传什么类型的文件

swift - 设置以编程方式创建的 UITextView 的插图

ios - 按 View Controller 两次

ios - SWIFT - NSTimer,传递用户信息

objective-c - 放置处理 UI 转换和操作的代码的最佳位置在哪里?

java - 如何在 Java GUI 中添加一行?

iOS Realm 更新 block 中的对象

ios - iOS 11 中的密码自动填充快速输入栏