键盘出现时向上移动UITextField

时间:2017-11-13 14:30:45

标签: swift uiscrollview uitextfield nsnotificationcenter uikeyboard

我最近开始按照互联网上的说明开发自己的应用程序。我只是一个初学者(不知道编码),因此可能会做一些我无法捕捉的非常愚蠢的错误。

在我的应用程序中,我遇到的情况是,每当我尝试键入电子邮件地址时,我的电子邮件文本字段都隐藏在键盘后面。我做了一些研究(关于堆栈溢出)并写了一段代码,假设移动我的文本字段,但它不是......我相信代码的整体结构是正确的(虽然我可能在这里错了)但它可能是只是一个小错误,使我的代码无效。

任何人都可以指导我在这里做错了吗?

下面是我写的代码: {

import UIKit
import WebKit
import CoreGraphics
import AVFoundation
import QuartzCore
import Foundation

class StudentSignUpViewController: UIViewController,UIScrollViewDelegate, UITextFieldDelegate {


@IBOutlet weak var yourEmail: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    //setting portrait
    AppUtility.lockOrientation(.portrait)

    //hide keyboard when click outside
    self.hideKeyboardWhenTappedAround()

    //hide keyboard when click on return
    self.yourEmail.delegate = self        
    self.scrollView.delegate = self


    //boarder line for yourEmail
    yourEmail.frame.size.height =  UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.05)
    yourEmail.font = UIFont.italicSystemFont(ofSize: UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.04))
    bottomBoader(BottomLine: "UrEmailTextBottomLine", length: 1.0, yourTextBox: yourEmail)
    yourEmail.applyCustomClearButton(yourTextBox: yourEmail)


    registerForKeyboardNotifications()
    deregisterFromKeyboardNotifications()

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

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

    AppUtility.lockOrientation(.portrait)
}

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

    AppUtility.lockOrientation(.all)
}


// ***************************************************  moving textfiles when keyborad present ***********************************************************


func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.yourEmail {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
    //self.scrollView.contentInset = UIEdgeInsets.zero
}

func textFieldDidBeginEditing( textField: UITextField){
    yourEmail = textField
}

func textFieldDidEndEditing(textField: UITextField){
    yourEmail = nil
}

4 个答案:

答案 0 :(得分:2)

问题是您registerForKeyboardNotifications()然后立即deregisterFromKeyboardNotifications(),因此您无法获得键盘通知。您应该取消注册到deinit

deinit {
    deregisterFromKeyboardNotifications()
}

修改

正如@matt指出你不需要deregisterFromKeyboardNotifications所以只需删除该代码(包括我对deinit的建议)

答案 1 :(得分:0)

将控件嵌入到故事板上的静态单元格的UITableView中,系统会让系统负责滚动。

答案 2 :(得分:0)

嘿兄弟为什么要调用viewDidLoad中的函数

registerForKeyboardNotifications()
deregisterFromKeyboardNotifications()

在viewDidLoad中只调用registerForKeyboardNotifications()并在deinit中调用deregisterFromKeyboardNotifications()

答案 3 :(得分:0)

最终解决方案工作正常,我已经从堆栈溢出中复制它并为我的目的稍微调整一下:

 var activeField: UITextField?

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height

    if let activeField = self.activeField {
        if activeField.frame.maxY > (scrollView.frame.height - keyboardSize!.height){
             self.scrollView.setContentOffset(CGPoint.init(x: 0, y: activeField.frame.maxY - (scrollView.frame.height - keyboardSize!.height) + 20), animated: true)
        } else {
            return
                    }

    print(activeField.frame.maxY)
    print(scrollView.frame.height)
    print(keyboardSize!.height)
    print(scrollView.frame.height - keyboardSize!.height)
    print(activeField.frame.maxY - (scrollView.frame.height - keyboardSize!.height) + 20)
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}