Skip to content

Instantly share code, notes, and snippets.

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/ca1b7760cd2ca31900879f9c9fff32a9 to your computer and use it in GitHub Desktop.
Save gngrwzrd/ca1b7760cd2ca31900879f9c9fff32a9 to your computer and use it in GitHub Desktop.
class FormFieldNavigator {
//...
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
}
//This is new, update return key type for all inputs
inputs.forEach { updateReturnKeyType(view: $0) }
}
//Below methods are all new.
//Updates the return key. First make sure we can by checking canSetReturnKey.
//Default will be either .next or .done.
//If a delegate implements the protocol then that will be used.
private func updateReturnKeyType(view:UIView) {
guard canSetReturnKey(view: view) else { return }
var retKeyType:UIReturnKeyType = returnKeyType(for: view)
if let customRetType = returnKeyType(view: view) {
retKeyType = customRetType
}
if let view = view as? UITextField {
view.returnKeyType = retKeyType
} else if let view = view as? UITextView {
view.returnKeyType = retKeyType
}
}
//Check if we can set the returnKeyType - default to true which will allow
//either .next, or .done return key type. Inputs can implement the protocol
//if they don't allow the return key to be set.
private func canSetReturnKey(view:UIView) -> Bool {
guard let delegate = inputDelegate(view: view) else { return true }
guard let options = delegate as? BLFormFieldNavigationReturnKeyTypeOptions else { return true }
return options.fieldNavigatorCanSetReturnKeyType
}
//Default return key type which is .next, or .done if the input is last.
private func returnKeyType(for input:UIView) -> UIReturnKeyType {
guard input is UITextField || input is UITextView else { return .default }
if responders.last == input {
return .done
}
return .next
}
//Custom return key type when the input delegate implements the protocol.
private func returnKeyType(view:UIView) -> UIReturnKeyType? {
guard let delegate = inputDelegate(view: view) else { return nil }
guard let options = delegate as? FormFieldNavigationReturnKeyTypeOptions else { return nil }
if view == responders.last {
return options.fieldNavigatorReturnKeyTypeWhenLast
}
return options.fieldNavigatorReturnKeyType
}
//Helper to get the delegate from a UITextField or UITextView.
private func inputDelegate(view:UIView) -> UIView? {
if let view = view as? UITextField {
return view.delegate as? UIView
}
if let view = view as? UITextView {
return view.delegate as? UIView
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment