CustomTextField.swift
struct CustomTextField: UIViewRepresentable {
@Binding var text: String
var font: UIFont = .init()
var textAlignment: NSTextAlignment = .left
var isFirstResponder: Bool
init(text: Binding<String>, isFirstResponder: Bool = false) {
self._text = text
self.isFirstResponder = isFirstResponder
}
func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.font = font
textField.textAlignment = textAlignment
textField.delegate = context.coordinator
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return textField
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
uiView.text = text
if isFirstResponder && !context.coordinator.didBecomeFirstResponder {
uiView.becomeFirstResponder()
context.coordinator.didBecomeFirstResponder = true
}
}
}
extension CustomTextField {
func makeCoordinator() -> CustomTextField.Coordinator {
Coordinator(text: $text)
}
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
var didBecomeFirstResponder = false
init(text: Binding<String>) {
_text = text
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
}
}
}
extension CustomTextField {
public func font(_ font: UIFont) -> CustomTextField {
var view = self
view.font = font
return view
}
public func textAlignment(_ alignment: NSTextAlignment) -> CustomTextField {
var view = self
view.textAlignment = alignment
return view
}
}
Content.swift
struct ContentView : View {
@State var text: String = ""
var body: some View {
CustomTextField(text: $text, isFirstResponder: true)
.borderStyle(.roundedRect)
.frame(width: 200, height: 40)
.background(Color.red)
}
}
iOS15以降は@FocusState
を使う
参考にしたのはこちら