Last active
October 26, 2020 15:03
-
-
Save gbougakov/1ca9baf00b1c5dac513a84bd841c5dde to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SATextField.swift | |
// Originally created by @valvolinne. Extracted into a separate file and improved by @gbougakov | |
// | |
import SwiftUI | |
import UIKit | |
class WrappableTextField: UITextField, UITextFieldDelegate { | |
var textFieldChangedHandler: ((String)->Void)? | |
var onCommitHandler: (()->Void)? | |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { | |
if let nextField = textField.superview?.superview?.viewWithTag(textField.tag + 1) as? UITextField { | |
nextField.becomeFirstResponder() | |
} else { | |
textField.resignFirstResponder() | |
} | |
return false | |
} | |
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { | |
if let currentValue = textField.text as NSString? { | |
let proposedValue = currentValue.replacingCharacters(in: range, with: string) | |
textFieldChangedHandler?(proposedValue as String) | |
} | |
return true | |
} | |
func textFieldDidEndEditing(_ textField: UITextField) { | |
onCommitHandler?() | |
} | |
} | |
struct SATextField: UIViewRepresentable { | |
private let tmpView = WrappableTextField() | |
//var exposed to SwiftUI object init | |
var tag:Int = 0 | |
var placeholder:String? | |
var changeHandler:((String)->Void)? | |
var onCommitHandler:(()->Void)? | |
var keyboardType: UIKeyboardType = UIKeyboardType.default | |
var borderStyle: UITextField.BorderStyle = UITextField.BorderStyle.roundedRect | |
var secure: Bool = false | |
func makeUIView(context: UIViewRepresentableContext<SATextField>) -> WrappableTextField { | |
tmpView.tag = tag | |
tmpView.delegate = tmpView | |
tmpView.placeholder = placeholder | |
tmpView.onCommitHandler = onCommitHandler | |
tmpView.textFieldChangedHandler = changeHandler | |
tmpView.keyboardType = keyboardType | |
tmpView.borderStyle = borderStyle | |
tmpView.isSecureTextEntry = secure | |
return tmpView | |
} | |
func updateUIView(_ uiView: WrappableTextField, context: UIViewRepresentableContext<SATextField>) { | |
uiView.setContentHuggingPriority(.defaultHigh, for: .vertical) | |
uiView.setContentHuggingPriority(.defaultLow, for: .horizontal) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment