0

최근 인터넷에서 지침에 따라 내 앱을 개발하기 시작했습니다. 나는 코딩에 대한 지식이없는 초보자 일 뿐이므로 나는 잡을 수없는 매우 어리석은 실수를 저지르고 있을지 모른다.키보드를 움직이면 UITextField가 올라갑니다.

내 앱에서 전자 메일 주소를 입력 할 때마다 전자 메일 텍스트 필드가 키보드 뒤에 숨어있는 상황에 직면하고 있습니다. 나는 (스택 오버플로에 대한) 약간의 연구를 수행하고 텍스트 필드를 이동한다고 가정하는 코드 조각을 작성했지만 그렇지 않다. 코드의 전체 구조가 옳다고 나는 믿는다. 내 코드를 비효율적으로 만드는 작은 실수.

내가 여기서 뭘 잘못하고 있는지 안내 할 수있는 사람이 있습니까?

아래 내가 쓴 코드의 조각 : {

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 
} 

답변

2

문제는 즉시 deregisterFromKeyboardNotifications() 그래서 당신이 점점되지 않는 키보드 알림 다음 registerForKeyboardNotifications() 및입니다입니다. 당신은 deinit에 등록 취소를 이동해야합니다 :

deinit { 
    deregisterFromKeyboardNotifications() 
} 

편집

을 @ 매트는 지적이

+0

실제로 등록을 취소 할 필요가 없습니다. 등록 취소에 대한 벌칙은 더 이상 없습니다. 그 걱정은 몇 년 전에 사라졌습니다. – matt

+0

@matt nice, 답을 업데이트하겠습니다. 에 { FUNC의 deregisterFromKeyboardNotifications() { // 제거 통지 : – sbarow

+0

안녕, 난 내가 무슨 짓을하는 것은 전체 코드의 코드 아래에 제거입니다 .. 코드에서하지만 운) (deregisterFromKeyboardNotifications을 제거한 후 코드를 실행하려고 키보드 나타나는 NotificationCenter.default.removeObserver (자기 이름 : NSNotification.Name.UIKeyboardWillShow 개체 : 무기 호) NotificationCenter.default.removeObserver (자기 이름 : NSNotification.Name.UIKeyboardWillHide 개체 : 무기 호) } } –

0
그래서 그냥 ( deinit 내 제안을 포함하여) 그 코드를 삭제 deregisterFromKeyboardNotifications 할 필요가 없습니다

Storyboard에 정적 셀이있는 UITableView에 컨트롤을 포함하면 시스템에서 스크롤을 처리 할 수 ​​있습니다.

0

헤이 형제 이유

의 viewDidLoad 호출에만 registerForKeyboardNotifications에서
registerForKeyboardNotifications() 
deregisterFromKeyboardNotifications() 

()와 deinit 호출 deregisterFromKeyboardNotifications()에있는 viewDidLoad의 기능 모두를 호출하는

잘 작동
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 
}