Created
February 1, 2022 15:52
-
-
Save Sam-Spencer/ad2f78f16e3adb24b1c3019d97aada39 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.