Last active
July 27, 2022 22:32
-
-
Save faganello60/6e5949af304980eaea0d517ba3dbf43e to your computer and use it in GitHub Desktop.
MaskTextField-SwiftUI.swift
This file contains 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
import SwiftUI | |
import Combine | |
public protocol Mask { | |
var maskFormat: String { get set } | |
func formateValue(_ value: String) -> String | |
} | |
extension Mask { | |
public func formateValue(_ value: String) -> String { | |
let cleanPhoneNumber = value.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() | |
let mask = maskFormat | |
var result = "" | |
var index = cleanPhoneNumber.startIndex | |
for ch in mask where index < cleanPhoneNumber.endIndex { | |
if ch == "#" { | |
result.append(cleanPhoneNumber[index]) | |
index = cleanPhoneNumber.index(after: index) | |
} else { | |
result.append(ch) | |
} | |
} | |
return result | |
} | |
} | |
public struct MSTextField: View { | |
@State private var focused: Bool = false | |
@Binding private var text: String | |
private let title: String | |
private let placeholder: String | |
private let mask: Mask? | |
public init(title: String, placeholder: String, text: Binding<String>, mask: Mask? = nil) { | |
self.title = title | |
self.placeholder = placeholder | |
self._text = text | |
self.mask = mask | |
} | |
public var body: some View { | |
VStack( | |
alignment: .leading, | |
spacing: DS.Spacing.Stack.tiny | |
) { | |
Text(title) | |
.style(size: .preMedium, weight: .regular) | |
TextField(placeholder, text: $text, onEditingChanged: { edit in | |
self.focused = edit | |
}) | |
.onReceive(Just(text), perform: { text in | |
self.text = mask?.formateValue(text) ?? text | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment