快速移动文本字段问题

标签 swift uitextfield keyboard-events

我有 2 个文本字段都放在 ImageView 的顶部。当键盘出现时,底部的文本字段应该向上移动。当 ImageView 为空时,底部文本字段会按预期向上移动,但是当 ImageView 中存在图像时,底部文本字段不会向上移动。执行时可以在 print 语句的帮助下看到 keyboardWillShow 函数没有执行。有人可以帮忙吗?

以下是我的代码

class ViewController: UIViewController, UITextFieldDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    @IBOutlet weak var actualImage: UIImageView!

    @IBOutlet weak var shareButton: UIButton!
    @IBOutlet weak var deleteButton: UIButton!
    @IBOutlet weak var topTextField: UITextField!
    @IBOutlet weak var bottomTextField: UITextField!
    var activeTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        topTextField.delegate = self
        bottomTextField.delegate = self

        //Animations
          topTextField.isHidden = true
          bottomTextField.isHidden = true
          shareButton.isEnabled = false
          deleteButton.isEnabled = false


        let center: NotificationCenter = NotificationCenter.default
        center.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    //Editing text Fields
    func textFieldDidBeginEditing(_ textField: UITextField) {
        activeTextField = textField
    }
    @objc func keyboardDidShow(notification: Notification) {
            print("keyboarddidshow")

        if activeTextField != nil {

            let info: NSDictionary = notification.userInfo! as NSDictionary
            let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
            let keyboardY = self.view.frame.size.height  - keyboardSize.height
            let textFieldY: CGFloat! = self.activeTextField.frame.origin.y


            if self.view.frame.origin.y >= 0{

                if textFieldY > (keyboardY - 80){

                    UIView.animate(withDuration: 0.25,delay:0.0,options:UIViewAnimationOptions.curveEaseIn, animations: {
                        self.view.frame = CGRect(x: 0, y: self.view.frame.origin.y - (textFieldY - (keyboardY - 80)), width: self.view.bounds.width, height: self.view.bounds.height)
                    }, completion: nil)
                }
            }
        }
    }

    @objc func keyboardWillHide(notification: Notification){

        print("switch field keyboard will hide")
        UIView.animate(withDuration: 0.25,delay:0.0,options:UIViewAnimationOptions.curveEaseIn, animations: {
            self.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)}, completion: nil
        )

    }


    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    override func viewDidDisappear(_ animated: Bool) {

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    //share button pressed
    @IBAction func sharePressed(_ sender: UIButton) {
        topTextField.borderStyle = .none
        topTextField.borderStyle = .none
        let image: UIImage = generateMemedImage()
        let shareImage = UIActivityViewController(activityItems: [image, topTextField,bottomTextField], applicationActivities: nil)
        present(shareImage, animated: true, completion: nil)

    }
    //allow selecting image from photo library
    @IBAction func selectFromGallery(_ sender: Any) {
        let gallery = UIImagePickerController()
        gallery.delegate = self
        gallery.sourceType = .photoLibrary
        present(gallery, animated: true, completion: nil)
    }

    @IBAction func selectFromCamera(_ sender: Any) {
        let gallery = UIImagePickerController()
        gallery.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            gallery.sourceType = .camera
            present(gallery, animated: true, completion: nil)

        } else {
             displayAlert(title: "Camera not available", message: "")

        }

    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        actualImage.image = selectedImage
        dismiss(animated: true, completion: nil)
        topTextField.isHidden = false
        bottomTextField.isHidden = false
        shareButton.isEnabled = true
        deleteButton.isEnabled = true
        topTextField.text = " "
        bottomTextField.text = " "

    }
    @IBAction func deletePressed(_ sender: Any) {
        actualImage.image = nil
        topTextField.isHidden = true
        bottomTextField.isHidden = true
        shareButton.isEnabled = false
        deleteButton.isEnabled = false
        topTextField.text = " "
        bottomTextField.text = " "
    }

    //display alert
    func displayAlert(title: String, message:String){
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }


    func generateMemedImage() -> UIImage {

        // Render view to an image
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 375, height: 517), false, 0)
        view.drawHierarchy(in: CGRect(x: 0, y: -75, width: view.bounds.size.width, height: view.bounds.size.height), afterScreenUpdates: true)
        let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return memedImage
    }

}

最佳答案

当您显示相机或图库时,将调用 viewDidDisappear,这会删除您对通知的订阅。也许你应该像这样订阅 viewDidAppear 中的通知:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let center: NotificationCenter = NotificationCenter.default
    center.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

关于快速移动文本字段问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49804502/

相关文章:

ios - 导航栏中的 UISearchBar 无法输入文本

javascript - 输入上的 keyup 事件不起作用

javascript - "KeyboardEvent.key"值跨浏览器一致吗?

ios - 为什么更改UILabel的文本不会在iOS 13上重置文本属性?

ios - 当我点击任何 Collection View 单元格(不点击最后一个单元格)时,如何移动另一个 View Controller ?

swift - 我的 Xcode 10.0 找不到我的 Iphone SE,因为它运行的是 ios 12.4

ios - 将用户文本字段输入附加到其他 View Controller 中的数组中

ios - 用户登录后清除密码文本字段

ios - 以编程方式创建 UItextfield,以后如何获取文本?

javascript - 如何使用 libphonenumber AsYouTypeFormatter 处理退格键