快速移动文本字段问题

时间:2018-04-12 19:30:44

标签: swift uitextfield keyboard-events

我有2个文本字段都放在图像视图的顶部。当键盘出现时,底部文本字段应该向上移动。当图像视图为空时,底部文本字段按预期向上移动,但是当图像存在于图像视图中时,底部文本字段不会向上移动。执行时可以在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
    }

}

1 个答案:

答案 0 :(得分:1)

当您显示相机或图库时,会调用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)
}