TextField with Custom Binding

I'm just playing with Combine, and I want to limit the number of letters that the text field can show. So I have the following lines of code.

import SwiftUI

struct ContentView: View {
	@State var messageText: String = ""
	
	var body: some View {
		let bindingMessage = Binding {
			messageText
		} set: {
			messageText = String($0.prefix(10))
			print(String($0.prefix(10)))
		}

		Form {
			TextField("Message", text: bindingMessage)
		}
	}
}

I'm expecting that the text field will show only the first 10 letters. But, as the screenshot below indicates, it shows the entire string. What am I doing wrong? Muchos Thankos. It sounds basic. Ugghhh...

  • I could do it with Combine. But that's not what I need. I need a solution with a custom binding.

Add a Comment

Replies

i am also seeing this same issue on iOS 17 only. the value in the getter for the custom binding is being ignored and the value input directly to the text field is being used. in my case i am adjusting the raw entry into a format of mm:ss filling in from left to right.