Skip to content

Instantly share code, notes, and snippets.

@gngrwzrd
Last active June 1, 2021 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gngrwzrd/ab503f9d75c19927da505535fe4df67d to your computer and use it in GitHub Desktop.
Save gngrwzrd/ab503f9d75c19927da505535fe4df67d to your computer and use it in GitHub Desktop.
class FormFieldNavigator {
weak var view:UIView? {
didSet {
if let _ = view {
update()
} else {
inputs = []
}
}
}
weak var firstResponder:UIView? {
get {
return _firstResponder()
} set {
_firstResponderStorage = newValue
_firstResponderStorage?.becomeFirstResponder()
}
}
private var _firstResponderStorage:UIView?
///All inputs found.
private var inputs:[UIView] = []
init(view:UIView? = nil) {
self.view = view
}
private func allInputs(view:UIView) -> [UIView] {
var inputs:[UIView] = []
for view in view.subviews {
if view is UITextField || view is UITextView {
inputs.append(view)
}
let subInputs = allInputs(view: view)
if subInputs.count > 0 {
inputs.append(contentsOf: subInputs)
}
}
return inputs
}
func update() {
guard let view = view else { return }
inputs = allInputs(view: view)
inputs.sort { view1, view2 in
let view1Frame = view1.convert(CGPoint.zero, to: nil)
let view2Frame = view2.convert(CGPoint.zero, to: nil)
if view1Frame.y == view2Frame.y {
return view1Frame.x < view2Frame.x
}
return view1Frame.y < view2Frame.y
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment