TextField에서 자동 포맷적용하기

👋 들어가기 전
이전 포스팅에서 TextField의 prompt를 알아봤는데, TextField 생성자에 또 하나의
흥미로운 파라미터를 발견했다.

뭔가 포맷관련된 내용인데 어떤 작용을 하는 지 알아보자.
🏁 학습할 내용
- ParseableFormatStyle
- ParseStrategy
- 자동 해시태그 포맷팅 만들기
🎨 ParseableFormatStyle
🧐 분석

- FormatStyle이란 프로토콜을 참조하고 있고
- parseStrategy라는 변수를 같고 있음
- Strategy라는 놈은 또 ParseStrategy라는 프로토콜을 채택
- FormatStyle의 FormatInput 타입 == Strategy.ParseOut 타입
- FormatStyle의 FormatOutput 타입 == Strategy.ParseInput 타입
🌠 FormatStyle


- 주어진 데이터 타입을 다른 데이터 타입으로 convert 해주는 역할할 때 채택함
- 주어진 데이터 타입 = FormatInput
- convert 된 타입 = FormatOut
- format 함수는 실제 convert 진행
- locale 함수는 포맷 스타일이 지역/언어 설정에 맞는 FormatStyle을 반환
♟️ ParseStrategy
🧐 분석

- 재료로 들어온 데이터 타입 = ParseInput
- parse 결과 타입 = ParseOutput
- 위에 Format쪽과 연관지어 보면 ParseStrategy는 입력 해석기 역할을 함
- Format에 사용될 데이터 타입을 ParseStrategy가 결정함
간단한 예시를 봐보자, text 타입을 살펴보자. TextField에 Int 타입이 들어가고 있다??
이게 바로 ParseStrategy의 역할이다. 여기서 Int로 들어가도, format할 때는 아마 String으로 넘겨준다.
이후 결과는 사진을 살펴보자.
정리하면, 값에 따라 보여질 textField내용은 format 함수의 리턴 값이고,
바인딩된 변수에 저장될 값은 parse 함수의 결과 값이다.
struct BoolFormatStyle: ParseableFormatStyle {
typealias FormatInput = Bool
typealias FormatOutput = String
var parseStrategy = BoolParseStrategy()
func format(_ value: Bool) -> String {
value ? "✅ Yes" : "❌ No"
}
}
struct BoolParseStrategy: ParseStrategy {
func parse(_ value: String) throws -> Bool {
let trimmed = value.lowercased().trimmingCharacters(in: .whitespaces)
switch trimmed {
case "yes", "✅ yes": return true
case "no", "❌ no": return false
default: fatalError()
}
}
}
public struct Dummy: View {
@State var text: Bool = true
public init() {}
public var body: some View {
VStack {
TextField("해시태그 입력", value: $text, format: BoolFormatStyle())
.textFieldStyle(.roundedBorder)
.padding()
Text("모델 값: \(text)")
}
}
}

출처
https://developer.apple.com/documentation/foundation/parseableformatstyle
ParseableFormatStyle | Apple Developer Documentation
A type that can convert a given input data type into a representation in an output type.
developer.apple.com
https://developer.apple.com/documentation/foundation/parseableformatstyle/strategy
Strategy | Apple Developer Documentation
There's never been a better time to develop for Apple platforms.
developer.apple.com