swiftuitextfield

SwiftUI TextField with vertical axis doesn't limit lines or characters


I'm experiencing issues with a TextField on the vertical axis in SwiftUI. I'm unable to limit the number of lines or characters. Everything works fine when the vertical axis parameter is removed. Here's my code:

@State private var text = ""

List{
   Section {
     TextField("placeholder", text: $text, axis: .vertical)
     .linelimit(3)
   }
}

I also tried to limit characters by going:

@State var textLimit: Int = 10

List{
   Section {
     TextField("placeholder", text: $text, axis: .vertical)
     .onChange(of: text){
          text = String(text.prefix(titleLimit))
     }
   }
}

But nothing seems to work. What am I doing wrong? Thanks.


Solution

  • When you do axis: .vertical it renders a multiline UITextView instead of single line UITextField. They are observing the hardware keyboard return key to submit the field but they forgot to handle the software keyboard return key and it will happily add lines FB17642828.

    As a work around you can search for the newline character, replace it, then end editing, e.g.

    @FocusState var isFocused
    ...
        .onChange(of: text) {
            if text.contains(where: { $0 == "\n" }) {
                print("Software keyboard return key pressed")
                // remove the newline
                text.removeAll(where: { $0 == "\n" })
                // End editing
                
            }
        }
        .onSubmit {
          // Hardware keyboard return pressed
        }
        .focused($isFocused)
    ...
    func submit() {
        isFocused = false
        // do other submit action
    }
                   
    

    I also noticed they aren't catching hardware keyboard tabs to end editing and move to next field. It just inserts a tab into the text.