moving a bar with UIScrollViewKeyboardDismissModeI

2019-01-31 22:54发布

I have a text field that I anchor to the top of the keyboard. I can't use inputAccessoryView since it's always shown. I'm able to observe keyboard hidden/shown notifications to move it up and down with the keyboard, but this doesn't appear to work with UIScrollViewKeyboardDismissModeInteractive. Is there a way to get constant feedback on the position of the keyboard to sync the animation?

7条回答
萌系小妹纸
2楼-- · 2019-01-31 23:43

Only CALayer position is updated interactively for Swift 4 on iPhone X iOS 11.2.2:

class MyValueObservingView: UIView {
    static let CALayerPositionChangeNotification = Notification.Name("CALayerPositionChangeNotification")
    static let CALayerPositionUserInfoKey = "position"

    override func willMove(toSuperview newSuperview: UIView?) {
        superview?.layer.removeObserver(self, forKeyPath: type(of: self).CALayerPositionUserInfoKey)
        newSuperview?.layer.addObserver(self, forKeyPath: type(of: self).CALayerPositionUserInfoKey, options: [.initial, .new], context: nil)
        super.willMove(toSuperview: newSuperview)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == type(of: self).CALayerPositionUserInfoKey, let position = change?[.newKey] as? CGPoint {
//            print("MyValueObservingView layer position changed to \(position)")
            NotificationCenter.default.post(name: type(of: self).CALayerPositionChangeNotification, object: self, userInfo: [type(of: self).CALayerPositionUserInfoKey: position])
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
}
查看更多
登录 后发表回答