如何设置文本字段字符限制SwiftUI



我正在使用SwiftUi版本2进行应用程序开发。我遇到了SwiftUI中可用的文本字段的问题。我不想再使用UITextField了。我想限制TextField中的字符数。我搜索了很多,找到了一些与此相关的答案,但这些答案不适用于SwiftUI版本2。

class textBindingManager: ObservableObject{
let characterLimit: Int
@Published var phoneNumber = "" {
didSet {
if phoneNumber.count > characterLimit && oldValue.count <= characterLimit {
phoneNumber = oldValue
}            
}
}
init(limit: Int = 10) {
characterLimit = limit
}    
}

struct ContentView: View {
@ObservedObject var textBindingManager = TextBindingManager(limit: 5)        
var body: some View {
TextField("Placeholder", text: $textBindingManager.phoneNumber)
}
}

无需在已发布的属性上使用didSet。您可以在TextField中添加一个修饰符,并将字符串值限制为其前缀,限制为字符限制:

import SwiftUI
struct ContentView: View {
@ObservedObject var textBindingManager = TextBindingManager(limit: 5)
var body: some View {
TextField("Placeholder", text: $textBindingManager.phoneNumber)
.padding()
.onChange(of: textBindingManager.phoneNumber, perform: editingChanged)
}
func editingChanged(_ value: String) {
textBindingManager.phoneNumber = String(value.prefix(textBindingManager.characterLimit))
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

class TextBindingManager: ObservableObject {
let characterLimit: Int
@Published var phoneNumber = ""
init(limit: Int = 10){
characterLimit = limit
}
}

以下应该是最简单的。它将字符数限制为10。

struct ContentView: View {
@State var searchKey: String = ""

var body: some View {
TextField("Enter text", text: $searchKey)
.onChange(of: searchKey) { newValue in
if newValue.count > 10 {
self.searchKey = String(newValue.prefix(10))
}
}
}
}

此解决方案将所有内容封装在一个新组件中。您可以很容易地将其调整为执行其他解析/模式检查。

struct ContentView : View {
@State private var myTextValue: String = ""

var body: some View {
LimitedTextField(value: $myTextValue, charLimit: 2)
}
}

struct LimitedTextField : View {
@State private var enteredString: String = ""
@Binding var underlyingString: String
let charLimit : Int

init(value: Binding<String>, charLimit: Int) {
_underlyingString = value
self.charLimit = charLimit
}

var body: some View {
HStack {
TextField("", text: $enteredString, onCommit: updateUnderlyingValue)
.onAppear(perform: { updateEnteredString(newUnderlyingString: underlyingString) })
.onChange(of: enteredString, perform: updateUndelyingString)
.onChange(of: underlyingString, perform: updateEnteredString)
}
}

func updateEnteredString(newUnderlyingString: String) {
enteredString = String(newUnderlyingString.prefix(charLimit))
}

func updateUndelyingString(newEnteredString: String) {
if newEnteredString.count > charLimit {
self.enteredString = String(newEnteredString.prefix(charLimit))
underlyingString = self.enteredString
}
}

func updateUnderlyingValue() {
underlyingString = enteredString
}
}

相关内容

  • 没有找到相关文章