본문 바로가기
ios 개발일지

[SwiftUI] 로그인 구현하기 #2 / UI 구현 - TextField, Button

by 리트레서 2024. 3. 27.
 

[SwiftUI] 로그인 구현하기 #1 / UI 구현 - Text, VStack

Github Projects, issues, branch 연계해서 만들기 https://to-continually-grow.tistory.com/5 Xcode Branch 추가 및 Push / ios https://to-continually-grow.tistory.com/4 xcode github 연동 / ios https://to-continually-grow.tistory.com/3 xcode 프로

to-continually-grow.tistory.com

전 게시물에서 SwiftUI로 로그인 UI를 구현하는 중 Text와 VStack의 사용을 다루어봤습니다. 오늘은 Textfield와 Button을 사용하여 로그인 화면을 조금 더 구현해보겠습니다.


 

 

우선 로그인을 하려면 email과 비밀번호가 필요하기 때문에 email과 Password TextField를 추가했습니다.

또한 TextField의 입력 값을 저장하는 변수인 id, password를 선언 및 공백으로 초기화합니다.

@State private var id: String = ""
@State private var password: String = ""

// 이메일 입력
TextField(
	"Email",
	text: $id
)
.padding(.bottom, 15)

// 비밀번호 입력
TextField(
	"Password",
	text: $password
)
.padding(.bottom, 15)

 

단순히 TextField를 추가하고 입력했을 때 두 가지 문제점이 생겼습니다.

1. 문자를 입력할 때 첫 문자는 대문자로 입력된다. 

2. 비밀번호는 보안을 위해 가려져서 나와야 되지만 다 공개되고 있다.

 

 

 

1번은 .textInputAutocapitalization(.never)를 사용하여 해결했습니다.

.textInputAutocapitalization(.never)

  - .characters : 모든 문자를 대문자로 표시

  - .sentences: 모든 문장의 첫 글자를 대문자로 시작

  - .words : 모든 단어의 첫 글자를 대문자로 시작

  _ .never : 어떤 것도 대문자를 자동으로 사용하지 않음 

 

TextInputAutocapitalization | Apple Developer Documentation

The kind of autocapitalization behavior applied during text input.

developer.apple.com

2번은 비밀번호를 나타내는 TextFieldSecurefield로 대체하여 해결했습니다.

Securefield는 입력된 문자열을 점으로 표시하여 민감한 정보를 숨길 수 있는 View입니다.

 

SecureField | Apple Developer Documentation

A control into which people securely enter private text.

developer.apple.com

@State private var id: String = ""
@State private var password: String = ""

// 이메일 입력
TextField(
	"Email",
	text: $id
)
.padding(.bottom, 15)
.textInputAutocapitalization(.never)

// 비밀번호 입력
SecureField(
	"Password",
	text: $password
)
.padding(.bottom, 15)
.textInputAutocapitalization(.never)

 

 

 

 

 

 

이제 Textfield를 꾸며보겠습니다.

padding을 수정하고, 배경 색을 지정하고, 텍스트 필드의 크기를 지정하고, 모서리를 둥글게 하였습니다.

@State private var id: String = ""
@State private var password: String = ""

// 이메일 입력
TextField(
	"Email",
	text: $id
)
padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 0))
.textInputAutocapitalization(.never)
.background(Color(red: 249/255, green: 245/255, blue: 244/255))
.frame(width: 280, height: 40)
.cornerRadius(7)

// 비밀번호 입력
SecureField(
	"Password",
	text: $password
)
padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 0))
.textInputAutocapitalization(.never)
.background(Color(red: 249/255, green: 245/255, blue: 244/255))
.frame(width: 280, height: 40)
.cornerRadius(7)

 

 

 

 

 

이제 버튼을 추가해보겠습니다.  action은 이벤트에 대한 처리를 나타내며 , label은 Button의 모습을 나타냅니다.

우선 action은 공백으로 두고 외형부터 정의하겠습니다.

@State private var id: String = ""
@State private var password: String = ""

// 이메일 입력
TextField(
	"Email",
	text: $id
)
.padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 0))
.textInputAutocapitalization(.never)
.background(Color(red: 249/255, green: 245/255, blue: 244/255))
.frame(width: 280, height: 40)
.cornerRadius(7)

// 비밀번호 입력
SecureField(
	"Password",
	text: $password
)
.padding(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 0))
.textInputAutocapitalization(.never)
.background(Color(red: 249/255, green: 245/255, blue: 244/255))
.frame(width: 280, height: 40)
.cornerRadius(7)


// 로그인 버튼
Button(action: {}, label: {
	Text("Sign in")
		.foregroundColor(.white)
		.frame(width: 280, height: 40)
		.background(Color.blue)
		.cornerRadius(5)
})

 

.foregroundColor : 글자 색을 정의합니다.

.frame : 텍스트 뷰의 크기를 지정합니다.

.background : 텍스트 뷰의 배경 색을 지정합니다.

.cornerRadius : 모서리의 둥글기를 지정합니다.

 

 

 

 

이제 버튼을 클릭하면 이메일과 패스워드가 print되고 가상 키보드가 닫히도록 하겠습니다.

 

참고로 시뮬레이터에서 가상키보드를 키고 싶으면 Command + K를 누르거나

계속 사용하는 것을 고정시키고 싶으면  I/O -> Keyboard -> Connect Hardware Keyboard를 체크하면됩니다.

 

 

 

 

 

View를 extension하여 키보드를 숨기는 hideKeyboard() 함수를 정의했습니다.

이후 버튼 action에 self.hideKeyboard()를 호출하여 버튼이 클릭 될 때 키보드가 종료되도록 했습니다.

또한 print("email: \(id), password: \(password)")로 id와 password의 값을 로그로 확인 할 수 있도록 했습니다.

@State private var id: String = ""
@State private var password: String = ""

extension View {
	
    // 키보드를 숨기는 함수 정의
    func hideKeyboard() {
    	// 시스템에 특정 동작을 보내는 역할
        UIApplication.shared.sendAction(
       		// Objective_c resignFirstResonder 메소드를 참조 키보드를 해제
            #selector(UIResponder.resignFirstResponder),
            to: nil, from: nil, for: nil
        )
    }
}

// 로그인 버튼
Button(action: {
	print("email: \(id), password: \(password)")
	self.hideKeyboard()
	}, label: {
		Text("Sign in")
			.foregroundColor(.white)
			.background(Color.blue)
			.cornerRadius(5)
	})
}

버튼 클릭 시 로그가 정상적으로 출력되는 것을 확인 할 수 있습니다.

 

 

아직 이메일 형식으로 입력되도록 검증하거나 공백인 상태에서 sign in 클릭 시 재 입력되도록 focus를 주는 등 로그인 기능은 구현하지 않았는데 UI 구현을 완료하고 기능 개발을 진행 할 때 게시물로 올리겠습니다!