apple/SwiftUI, Combine

SwiftUI TextField, SecureField

lgvv 2022. 5. 23. 13:27

SwiftUI TextField, SecureField

 

UIKit에서는 익숙했던 것들인데, SwiftUI에서는 낯설다.

  • TextField는 UITextField와 같다. 줄바꿈이 안된다.
    • 줄바꿈은 TextEditor
  • SecureField는 password를 입력할 때, 글자가 보이지 않게 가려주는 UI
 

샘플 코드

import SwiftUI

struct ContentView: View {
    
    @State private var username: String = ""
    @State private var password: String = ""
    
    var body: some View {
        
        VStack(spacing: 10){
            
            HStack {
                TextField("사용자 이름", text: $username)
                    .autocapitalization(.none) // 첫글자 자동으로 대문자 방지
                    .disableAutocorrection(true) // 대문자로 만들어주는 옵션 나타나는거 방지
                    .textFieldStyle(RoundedBorderTextFieldStyle()) // textField 옵션
                Button(action: {
                    self.username = "" 
                }){
                    if(self.username.count > 0) { // 글자가 있을 경우에만 이미지가 나타나게끔
                        Image(systemName: "multiply.circle.fill")
                        .font(.system(size: 25))
                        .foregroundColor(.secondary)
                    }
                    
                }
            }
            
            HStack{
                SecureField("비밀번호", text: $password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                Button(action: {
                    self.password = ""
                }){
                    if(self.password.count > 0){
                        Image(systemName: "multiply.circle.fill")
                        .font(.system(size: 25))
                        .foregroundColor(.secondary)
                    }
                    
                }
            }
            
            
            Text("입력한 비번 : \(password)")
            
        }.padding(.horizontal, 50)
        
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

 

결과물 UI