Skip to content

Instantly share code, notes, and snippets.

@Sam-Spencer
Created February 1, 2022 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sam-Spencer/ad2f78f16e3adb24b1c3019d97aada39 to your computer and use it in GitHub Desktop.
Save Sam-Spencer/ad2f78f16e3adb24b1c3019d97aada39 to your computer and use it in GitHub Desktop.
//
// TextLimiter.swift
//
//
// Created by Sam Spencer on 2/1/22.
//
import Foundation
import SwiftUI
public class TextLimiter: ObservableObject {
private let limit: Int
public init(limit: Int) {
self.limit = limit
}
@Published public var value = "" {
didSet {
if value.count > self.limit {
value = String(value.prefix(self.limit))
self.hasReachedLimit = true
} else {
self.hasReachedLimit = false
}
}
}
@Published public var hasReachedLimit = false
}
/// Demo SwiftUI View
struct DemoView: View {
@ObservedObject var password = TextLimiter(limit: 32)
var body: some View {
TextField("32 character password", text: $password.value)
.padding()
}
}
@Sam-Spencer
Copy link
Author

A semi-generic solution to validate a SwiftUI TextField's content as its changed, and make on-the-fly validation or changes to the value of the input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment