안녕하세요. 린다입니다.
SwiftUI에는 TextEditor에 배경색을 넣거나 다양한 UI로써 보이도록 하고
싶다면, 커스텀을 해야하는데요.
이번 SYM을 배포하면서 구현했던 TextEditor를 공유해보려고 합니다.
저희의 TextEditor 조건은 2가지였어요.
1. 글자수 200 미만만 입력 가능한 TextEditor
2. Placeholder가 있는 TextEditor
코드 공유
struct CustomTextEditorStyle: ViewModifier {
let placeholder: String
@Binding var text: String
func body(content: Content) -> some View {
content
.padding(15)
.background(alignment: .topLeading) {
if text.isEmpty {
Text(placeholder)
.lineSpacing(10)
.padding(20)
.padding(.top, 2)
.font(.system(size: 14))
.foregroundColor(Color(UIColor.systemGray2))
}
}
.textInputAutocapitalization(.none) // 첫 시작 대문자 막기
.autocorrectionDisabled()
.background(Color(UIColor.systemGray6))
.clipShape(RoundedRectangle(cornerRadius: 20))
.scrollContentBackground(.hidden)
.font(.system(size: 14))
.overlay(alignment: .bottomTrailing) {
Text("\(text.count) / 200")
.font(.system(size: 12))
.foregroundColor(Color(UIColor.systemGray2))
.padding(.trailing, 15)
.padding(.bottom, 15)
.onChange(of: text) { newValue in
if newValue.count > 200 {
text = String(newValue.prefix(200))
}
}
}
}
}
extension TextEditor {
func customStyleEditor(placeholder: String, userInput: Binding<String>) -> some View {
self.modifier(CustomTextEditorStyle(placeholder: placeholder, text: userInput))
}
}
글자수를 표현해주기 위해서 @Binding을 통해서 값을 받아오구요.
그래서 받아져서 오는 글자 수가 빈값이 아니라면 placeholder가 없어지구요.
overlay를 통해서 글자수를 보여주고 있습니다.
그리고 위에서 200자 제한을 하고 있는 조건은 onChange를 통해서 count가 200이상이라면
prefix를 통해 우선 입력된 값의 200자만 가져오는 형식으로 구현해놓았어요.
Extension으로 modifier화 했기 때문에 사용은 이렇게 하면 됩니다.
struct CustomTextEditor: View {
@State private var text: String = ""
private let placeholder: String = "예) 친구를 만나서 영화도 보고 맛있는 것도 먹었어"
var body: some View {
VStack {
TextEditor(text: $text)
.customStyleEditor(placeholder: placeholder, userInput: $text)
.frame(height: 200)
.padding()
}
}
}
오늘은 이렇게 간단하게 구현했던 방법을 공유해봅니다!
도움이 되시면 좋겠어요.
끝!
'Swift > SwiftUI' 카테고리의 다른 글
SwiftUI, Layout 프로세스를 알아보자2 (feat, offset과 position) (0) | 2024.03.28 |
---|---|
SwiftUI, Layout과 Alignment을 알아보자 (2019 WWDC) (1) | 2024.03.28 |
SwiftUI, Line Height 명확하게 설정하기 (feat, linespacing) (0) | 2024.03.02 |
SwiftUI, TextField에서 한글과 영어만 입력받는 방법 (특수문자, 초성 제외하기) (0) | 2024.02.22 |
SwiftUI로 Apple Login 구현 시 Button Custom을 쉽게 구현하는 방법 - (.blendMode 사용기) (0) | 2024.02.09 |