1

Using UITextField in SwiftUI I found a problem when the text overflow the UITextField width. Instead of the UITextField fixate the size and scroll the text, it grow until overflow the screen width.

I tried some methods, like put fixedSize() in AppTextField, set a frame to UITextField, but I don't found a way to fix this.

TextField with few characters

TextField on exceeding the width limit

App Screen

struct ContentView: View {
    
    @State var text = ""
    
    var body: some View {
        VStack {
            AppTextField(text: $text)
                .frame(height: 48)
                .padding(.horizontal, 16)
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(lineWidth: 1)
                )
        }
        .padding(.horizontal, 16)
    }
}

AppTextField

import Foundation
import UIKit
import SwiftUI

struct AppTextField: UIViewRepresentable {
    
    @Binding var text: String
    
    init(text: Binding<String>) {
        self._text = text
    }
    
    func makeUIView(context: UIViewRepresentableContext<AppTextField>) -> UITextField {
        let textField = UITextField(frame: .zero)
        textField.delegate = context.coordinator
        
        return textField
    }

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

    func updateUIView(_ textField: UITextField, context: UIViewRepresentableContext<AppTextField>) {
        textField.text = text
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {

        @Binding var text: String

        init(text: Binding<String>) {
            self._text = text
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            guard let text = textField.text else {
                return
            }
            
            DispatchQueue.main.async {
                self.text = text
            }
        }
        
    }
}

0 Answers0