code

Swift의 userInfo에서 키보드 크기 가져 오기

codestyles 2020. 10. 11. 10:36
반응형

Swift의 userInfo에서 키보드 크기 가져 오기


키보드가 나타날 때 뷰를 위로 이동하는 코드를 추가하려고 시도했지만 Objective-C 예제를 Swift로 변환하는 데 문제가 있습니다. 나는 약간의 진전을 이루었지만 특정 라인에 갇혀 있습니다.

다음은 내가 따라온 두 가지 자습서 / 질문입니다.

Swift http://www.ioscreator.com/tutorials/move-view-when-keyboard-appears를 사용하여 키패드가 나타날 때 UIViewController의 콘텐츠를 위로 이동하는 방법

현재 가지고있는 코드는 다음과 같습니다.

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
    UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    let frame = self.budgetEntryView.frame
    frame.origin.y = frame.origin.y - keyboardSize
    self.budgetEntryView.frame = frame
}

func keyboardWillHide(notification: NSNotification) {
    //
}

현재이 줄에 오류가 발생합니다.

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))

누군가가이 코드 줄이 무엇인지 알려줄 수 있다면 나머지는 직접 알아 내야합니다.


라인에 몇 가지 문제가 있습니다

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
  • notification.userInfo선택적 사전을 반환 [NSObject : AnyObject]?하므로 값에 액세스하기 전에 래핑을 해제해야합니다.
  • Objective-C NSDictionary는 Swift 네이티브 사전에 매핑되므로 dict[key]값에 액세스하려면 사전 아래 첨자 구문 ( )을 사용해야합니다.
  • NSValue호출 할 수 있도록 값을 캐스트해야 CGRectValue합니다.

이 모든 것은 선택적 할당, 선택적 연결 및 선택적 캐스트의 조합으로 달성 할 수 있습니다.

if let userInfo = notification.userInfo {
   if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
       // ...
   } else {
       // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
   }
} else {
   // no userInfo dictionary in notification
}

또는 한 단계로 :

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}

Swift 3.0.1 (Xcode 8.1) 업데이트 :

if let userInfo = notification.userInfo {
    if let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
        let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
        // ...
    } else {
        // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
    }
} else {
    // no userInfo dictionary in notification
}

또는 한 단계로 :

if let keyboardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}

더 적은 코드의 경우 THIS를 살펴보십시오.

정말 도움이되었습니다. 뷰 컨트롤러에 뷰 제약을 포함하고 추가 한 두 옵저버를 사용하기 만하면됩니다. 그런 다음 다음 방법을 사용하십시오 (여기서는 tableView를 이동한다고 가정합니다)

func keyboardWillShow(sender: NSNotification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
                tableViewBottomConstraint.constant = keyboardHeight
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.view.layoutIfNeeded()
                })
            }
        }
    }

func keyboardWillHide(sender: NSNotification) {
if let userInfo = sender.userInfo {
  if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
    tableViewBottomConstraint.constant = 0.0
    UIView.animateWithDuration(0.25, animations: { () -> Void in self.view.layoutIfNeeded() })
  }
} }

뷰 자체를 조작하는 대신 스토리 보드를 사용하는 경우 자동 레이아웃을 활용할 수 있습니다.

(이것은 Nicholas 's Answer의 정리 된 버전입니다)

키보드의 모양과 사라짐을 알리도록 알림 센터를 설정하십시오.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)

}

관찰자가 더 이상 필요하지 않으면 제거해야합니다.

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: self.view.window)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window)
}

스토리 보드 내에서 하단 제약을 설정합니다. 해당 제약의 출구를 만듭니다.

여기에 이미지 설명 입력

키보드가 표시되거나 숨겨 질 때 제약 조건의 상수 속성을 설정합니다.

func keyboardWillShow(notification: NSNotification) {
    guard let keyboardHeight = (notification.userInfo! as NSDictionary).objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size.height else {
        return
    }
    nameOfOutlet.constant = keyboardHeight
    view.layoutIfNeeded()
}

func keyboardWillHide(notification: NSNotification) {
    nameOfOutlet.constant = 0.0
    view.layoutIfNeeded()
}

이제 키보드가 나타나거나 사라질 때마다 자동 레이아웃이 모든 것을 처리합니다.


스위프트 2

func keyboardWasShown(notification:NSNotification) {
        guard let info:[NSObject:AnyObject] = notification.userInfo,
            let keyboardSize:CGSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size else { return }

        let insets:UIEdgeInsets = UIEdgeInsetsMake(self.scrollView.contentInset.top, 0.0, keyboardSize.height, 0.0)

        self.scrollView.contentInset = insets
        self.scrollView.scrollIndicatorInsets = insets
    }

스위프트 3

func keyboardWasShown(notification:NSNotification) {
    guard let info:[AnyHashable:Any] = notification.userInfo,
        let keyboardSize:CGSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size else { return }

    let insets:UIEdgeInsets = UIEdgeInsets(top: self.scrollView.contentInset.top, left: 0.0, bottom: keyboardSize.height, right: 0.0)

    self.scrollView.contentInset = insets
    self.scrollView.scrollIndicatorInsets = insets
}

이것은 나를 도왔습니다 : https://developer.apple.com/library/ios/samplecode/UICatalog/Listings/Swift_UICatalog_TextViewController_swift.html

let userInfo = notification.userInfo!

let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue
let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue()
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()

이 한 줄을 줄에 사용할 수 있습니다.

var keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size

Swift 3 : 업데이트

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}

Swift-keyboardWillShowNotification에서의 키보드 높이

키보드 Will / did Show / hide Notifications의 데이터를 사용하여 제약 조건 또는 기타 값을 키보드 크기로 늘리거나 줄일 수 있습니다.

레이아웃 제약

이 최소 코드는 키보드가 크기에 따라 제약 조건을 표시하고 업데이트한다는 알림을 등록합니다.

@IBOutlet weak var keyboardConstraint: NSLayoutConstraint!
let keyboardConstraintMargin:CGFloat = 20

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
        if let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect {
            self.keyboardConstraint.constant = keyboardSize.height + self.keyboardConstraintMargin
        }
    }
    NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: nil) { (notification) in
        self.keyboardConstraint.constant = self.keyboardConstraintMargin
    }
}

ScrollView 사용

같은 방식으로 키보드 크기에 따라 스크롤 뷰의 내용 삽입을 업데이트합니다.

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
  super.viewDidLoad()
  NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
    if let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect {
      let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
      self.scrollView.contentInset = insets
      self.scrollView.scrollIndicatorInsets = insets
    }
  }
  NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: nil) { (notification) in
    let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    self.scrollView.contentInset = insets
    self.scrollView.scrollIndicatorInsets = insets
  }
}

스위프트 3.0

다음은 키보드 크기를 검색하고이를 사용하여 뷰를 위쪽으로 애니메이션하는 예입니다. 제 경우에는 사용자가 입력을 시작할 때 UITextFields가 포함 된 UIView를 위로 이동하여 양식을 완성하고 하단에 제출 버튼을 계속 볼 수 있습니다.

애니메이션을 적용하려는 뷰 하단 공간 제약 조건콘센트를 추가하고 이름을 myViewsBottomSpaceConstraint다음 과 같이 지정했습니다 .

@IBOutlet weak var myViewsBottomSpaceConstraint: NSLayoutConstraint!

그런 다음 신속한 클래스에 다음 코드를 추가했습니다.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}

func keyboardWillShow(notification: NSNotification) {

    let userInfo = notification.userInfo as! [String: NSObject] as NSDictionary
    let keyboardFrame = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! CGRect
    let keyboardHeight = keyboardFrame.height
    myViewsBottomSpaceConstraint.constant = keyboardHeight
    view.layoutIfNeeded()
}

func keyboardWillHide(notification: NSNotification) {
    myViewsBottomSpaceConstraint.constant = 0.0
    view.layoutIfNeeded()
}

세부

xCode 8.2.1, 신속한 3

암호

키보드 알림

import Foundation

class KeyboardNotifications {

    fileprivate var _isEnabled: Bool
    fileprivate var notifications:  [KeyboardNotificationsType]
    fileprivate var delegate: KeyboardNotificationsDelegate

    init(notifications: [KeyboardNotificationsType], delegate: KeyboardNotificationsDelegate) {
        _isEnabled = false
        self.notifications = notifications
        self.delegate = delegate
    }

    deinit {
        if isEnabled {
            isEnabled = false
        }
    }
}

// MARK: - enums

extension KeyboardNotifications {

    enum KeyboardNotificationsType {
        case willShow, willHide, didShow, didHide

        var selector: Selector {
            switch self {

            case .willShow:
                return #selector(KeyboardNotifications.keyboardWillShow(notification:))

            case .willHide:
                return #selector(KeyboardNotifications.keyboardWillHide(notification:))

            case .didShow:
                return #selector(KeyboardNotifications.keyboardDidShow(notification:))

            case .didHide:
                return #selector(KeyboardNotifications.keyboardDidHide(notification:))

            }
        }

        var notificationName: NSNotification.Name {
            switch self {

            case .willShow:
                return .UIKeyboardWillShow

            case .willHide:
                return .UIKeyboardWillHide

            case .didShow:
                return .UIKeyboardDidShow

            case .didHide:
                return .UIKeyboardDidHide
            }
        }
    }
}

// MARK: - isEnabled

extension KeyboardNotifications {

    private func addObserver(type: KeyboardNotificationsType) {
        NotificationCenter.default.addObserver(self, selector: type.selector, name: type.notificationName, object: nil)
        print("\(type.notificationName.rawValue) inited")
    }

    var isEnabled: Bool {
        set {
            if newValue {

                for notificaton in notifications {
                    addObserver(type: notificaton)
                }
            } else {
                NotificationCenter.default.removeObserver(self)
                print("Keyboard notifications deinited")
            }
            _isEnabled = newValue
        }

        get {
            return _isEnabled
        }
    }

}

// MARK: - Notification functions

extension KeyboardNotifications {

    @objc
    func keyboardWillShow(notification: NSNotification) {
        delegate.keyboardWillShow?(notification: notification)
    }

    @objc
    func keyboardWillHide(notification: NSNotification) {
        delegate.keyboardWillHide?(notification: notification)
    }

    @objc
    func keyboardDidShow(notification: NSNotification) {
        delegate.keyboardDidShow?(notification: notification)
    }

    @objc
    func keyboardDidHide(notification: NSNotification) {
        delegate.keyboardDidHide?(notification: notification)
    }
}

KeyboardNotificationsDelegate

import Foundation

@objc
protocol KeyboardNotificationsDelegate {

    @objc optional func keyboardWillShow(notification: NSNotification)
    @objc optional func keyboardWillHide(notification: NSNotification)
    @objc optional func keyboardDidShow(notification: NSNotification)
    @objc optional func keyboardDidHide(notification: NSNotification)
}

용법

 class ViewController: UIViewController {
      private var keyboardNotifications: KeyboardNotifications!
      override func viewDidLoad() {
           super.viewDidLoad()
           ...
            keyboardNotifications = KeyboardNotifications(notifications: [.willShow, .willHide, .didShow, .didHide], delegate: self)
      }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        keyboardNotifications.isEnabled = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        keyboardNotifications.isEnabled = false
    }

 }

 extension ViewController: KeyboardNotificationsDelegate {

    // If you don't need this func you can remove it
    func keyboardWillShow(notification: NSNotification) {
           ...
    }

    // If you don't need this func you can remove it
    func keyboardWillHide(notification: NSNotification) {
           ...
    }

    // If you don't need this func you can remove it
    func keyboardDidShow(notification: NSNotification) {
           ...
    }

    // If you don't need this func you can remove it
    func keyboardDidHide(notification: NSNotification) {
           ...
    }
}

전체 샘플

import UIKit

class ViewController: UIViewController {

    private var keyboardNotifications: KeyboardNotifications!
    private var textField = UITextField(frame: CGRect(x: 40, y: 40, width: 200, height: 30))

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(textField)

        // when you will tap on view (background) the keyboard will hide
        // read about view.disableKeybordWhenTapped here: http://stackoverflow.com/a/42187286/4488252
        view.disableKeybordWhenTapped = true

        keyboardNotifications = KeyboardNotifications(notifications: [.willShow, .willHide, .didShow, .didHide], delegate: self)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        keyboardNotifications.isEnabled = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        keyboardNotifications.isEnabled = false
    }

}

 extension ViewController: KeyboardNotificationsDelegate {

    // If you don't need this func you can remove it
    func keyboardWillShow(notification: NSNotification) {
        print("keyboardWillShow")
        let userInfo = notification.userInfo as! [String: NSObject]
        let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        print("keyboardFrame: \(keyboardFrame)")
    }

    // If you don't need this func you can remove it
    func keyboardWillHide(notification: NSNotification) {
        print("keyboardWillHide")
    }

    // If you don't need this func you can remove it
    func keyboardDidShow(notification: NSNotification) {
        print("keyboardDidShow")
    }

    // If you don't need this func you can remove it
    func keyboardDidHide(notification: NSNotification) {
 print("keyboardDidHide")
    }
}

결과

여기에 이미지 설명 입력

로그

여기에 이미지 설명 입력


xamarin의 경우 c # 6을 사용할 수 있습니다.

private void KeyboardWillChangeFrame(NSNotification notification)
{
        var keyboardSize = notification.UserInfo.ValueForKey(UIKeyboard.FrameEndUserInfoKey) as NSValue;
        if (keyboardSize != null)
        {
            var rect= keyboardSize.CGRectValue;
            //do your stuff here
        }
}

C # 7

  private void KeyboardWillChangeFrame(NSNotification notification)
   {
       if (!(notification.UserInfo.ValueForKey(UIKeyboard.FrameEndUserInfoKey) is NSValue keyboardSize)) return;
       var rect= keyboardSize.CGRectValue;
   }

스위프트 4.2 당신은 UIResponder.keyboardFrameEndUserInfoKey을 사용할 수 있습니다

guard let userInfo = notification.userInfo , let keyboardFrame:CGRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect  else { return  }```

참고 URL : https://stackoverflow.com/questions/25451001/getting-keyboard-size-from-userinfo-in-swift

반응형