0

Creating a text field in SwiftUI using UI kit. However, the text is displayed as overflowing. What should I add to the custom?

enter image description here Originally, I want to make this red area a text field area.

enter image description here

struct FirstResponderTextField: UIViewRepresentable {
    @Binding var text: String
    let placeholder: String
    class Coordinator: NSObject, UITextFieldDelegate {

        @Binding var text: String
        var becameFirstResponder = false
        init(text: Binding<String>) {
            self ._text = text
        }
        func textFieldDidChangeSelection(_ textField: UITextField) {
            text = textField.text ?? ""
        }
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(text: $text)

    }
    func makeUIView(context: Context) -> some UIView {
        let textField = UITextField()
        textField.font = UIFont.systemFont(ofSize: 40, weight: .bold).rounded()
        textField.delegate = context.coordinator
        textField.placeholder = placeholder
        return textField
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
        if !context.coordinator.becameFirstResponder {
            uiView.becomeFirstResponder()
            context.coordinator.becameFirstResponder = true
        }
    }
}
extension UIFont {
    func rounded() -> UIFont {
        if let descriptor = self.fontDescriptor.withDesign(.rounded) {
            let fontSize = self.pointSize
            return UIFont(descriptor: descriptor, size: fontSize)
        } else {
            return self
        }
    }
}

I'm new to SwiftUI and would appreciate any comments or feedback.

toukyou
  • 31
  • 4
  • Does this answer your question https://stackoverflow.com/a/59193838/12299030? – Asperi Feb 06 '21 at 20:20
  • Thanks for the perfect answer! Now I can finish my first product in my life!!! I'm glad you gave me a great answer! – toukyou Feb 06 '21 at 20:57

0 Answers0