SwiftUI TextField max length

后端 未结 6 934
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 06:52

Is it possible to set a maximum length for TextField? I was thinking of handling it using onEditingChanged event but it is only called when the us

6条回答
  •  遥遥无期
    2020-11-30 07:11

    Regarding the reply of @Paulw11, for the latest Betas I made the UserData class work again like that:

    final class UserData: ObservableObject {
        let didChange = PassthroughSubject()
        var textValue = "" {
            didSet {
                textValue = String(textValue.prefix(8))
                didChange.send(self)
            }
        }
    }
    

    I changed willSet to didSet because the prefix was immediately overwritten by the user`s input. So using this solution with didSet, you will realize that the input is cropped right after the user typed it in.

提交回复
热议问题