Limit TextField to x amount of characters using SwiftUI

落爺英雄遲暮 提交于 2019-12-11 16:29:28

问题


Using iOS13.2, Swift-5.1.2, Xcode-11.2, I try the following:

I want to use a TextField. The user shall only be able to enter x-amount of characters into the TextField.

My code looks as follows:

import Combine
import SwiftUI

class Entry: ObservableObject {

  @Published var entry = "" {
    didSet {
        entry = String(entry.prefix(6)) // trying to limit to 6 characters
    }
  }
}

And in the above code, there is already the exception line.

I can see that the didSet{...} is wrong (since we end up in an endless loop setting/didSetting again and again)...

What is a better way to limit a TextField to x-amount of characters ?

Here is the rest of the code:

struct NumberView: View {
    var body: some View {

        Group {
            HStack {
                Spacer()
                NumberIcon(number: 1)
                NumberIcon(number: 2)
                NumberIcon(number: 3)
                NumberIcon(number: 4)
                NumberIcon(number: 5)
                NumberIcon(number: 6)
                Spacer()
            }
         }
    }
}
struct NumberIcon: View {
    @ObservedObject private var entry = Entry()
    var number: Int = 0
    var body: some View {
        TextField(" ", text: $entry.entry, onEditingChanged: { editing in
            print(editing)
            print(self.$entry)
        })
            .padding()
            .foregroundColor(Color.black)
            .background(Color.green)
            .font(.largeTitle)
            .lineLimit(1)
            .cornerRadius(16.0)
            .clipped()
            .keyboardType(.numberPad)
    }
}

struct NumberView_Previews: PreviewProvider {
    static var previews: some View {
        NumberView()
    }
}

I know that there are UIKit wrapper possibilities to use the good-old shouldChangeCharactersIn delegate methods form UITextFieldDelegate - but I would like to implement the character limitation purely with SwiftUI (no UIKit code). How can I do that ?


回答1:


The easiest way to achive this in SwiftUI is just to disable the TextField when the maximum number of characters is reached:

struct LimittedTextField: View {

    @State private var entry = ""

    let characterLimit = 6

    var body: some View {
        TextField("", text: $entry)
            .disabled(entry.count > (characterLimit - 1))
    }
}



回答2:


Thanks to this answer here, I found a solution:

The Entry class can be rewritten:

class Entry: ObservableObject {

    let characterLimit = 6   // limiting to 6 characters
    @Published var entry = "" {
        didSet {
            if entry.count > characterLimit && oldValue.count <= characterLimit {
                entry = oldValue
            }
        }
    }
}


来源:https://stackoverflow.com/questions/58672761/limit-textfield-to-x-amount-of-characters-using-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!