clamp
Clamp
clamp
글쓰기 관리
전체 방문자
오늘
어제
  • 분류 전체보기 (509)
    • IOS (85)
    • SwiftUI+TCA+Combine (9)
    • RxSwift + MVVM (56)
    • Clean Architecture (12)
    • SWIFT (56)
    • iOS - TDD (2)
    • 디자인패턴 (4)
    • CS (56)
      • 알고리즘 (29)
      • 운영체제 (15)
      • 자료구조 (2)
      • 네트워킹 (4)
      • 기타 (6)
    • 회고 (0)
    • Firebase (18)
    • SwiftUI (10)
    • iOS - UIKit (11)
    • iOS - 오픈소스 (6)
    • 코딩테스트 (166)
      • 프로그래머스 (164)
    • 정보처리기사 (14)
    • GitHub (2)
글쓰기 / 관리자

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • uikit
  • Swift
  • Q
  • ㅅ

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
clamp

Clamp

UIKit - UITextfield
iOS - UIKit

UIKit - UITextfield

2022. 3. 31. 17:05

UITextField:

- 텍스트를 편집하기 위한 객체, 사용자가 클릭하면 텍스트를 입력, 수정 할 수 있다.

- 여러줄을 입력할 수 없고 '한'줄만 가능하다(여러줄을 하기위해선 UITextView)

 

TextField.becomeFirstResponder() 화면이 넘어가면 자연스럽게 커서가 텍스트필드로 넘어오고 텍스트모드가 됨.


textField.keyboardType = .emailAddress  // 텍스트 필드의 키보드 스타일
textField.returnKeyType = .done         // 엔터버튼? 의 모드
textField.placeholder = "이메일 입력"      // placeholder
textField.borderStyle = .roundedRect    // 선 스타일

textField.isSecureTextEntry = true	   // 비밀번호 따위를 *로 표시
textField.clearButtonMode = .always    // clear버튼(전체삭제버튼) 모드

tf.frame.size.height = 48			//높이 48
tf.backgroundColor = .clear			//배경색 투명
tf.textColor = .white				//글자색 흰색
tf.tintColor = .white				
tf.autocapitalizationType = .none	//자동으로 앞글자를 대문자로 바꿔주는지? none
tf.autocorrectionType = .no			//자동으로 틀린글자 고쳐주는지 no
tf.spellCheckingType = .no			//스펠링 체크

leftView = spacer           // textfile는 leftView라는 왼쪽에 배치되는 뷰를 갖고있따. 일반적으로 텍스트필드의 아이콘, 버튼, 기타뷰를 표시하는데 사용된다. leftView는 이미지, 레이블, 다른 뷰를 할당할 수 있다.
leftViewMode = .always      // 이 뷰를 표시하려면 leftViewMode라는 속성을 설정해야한다. 이를 사용해 아이콘, 여백등을 지정할 수 있다.

//키보드를 띄움
textField.becomeFirstResponder() // textField를 FirstResponder로
// ➡️➡️ 텍스트필드가 First응답객체가 되면 키보드가 올라옴 => 키보드를 띄움!!

// 키보드를 내림
textField.resignFirstResponder() // textField를 resing(FirstResponder)의 반대


	
// 배경 클릭시 키보드 내림  ==> view 에 터치가 들어오면 에디팅모드를 끝냄.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)  //firstresponder가 전부 사라짐
    }
    
// 입력 시작시 키보드 올림  ==> textField delegate
func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.becomeFirstResponder()
}

//글자수를 10개로 제한
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let maxLength = 10
        guard let text = textField.text else { return true }
        let newlength = text.count + string.count - range.length
        return newlength < maxLength
    }

TextField Delegate

- 유저가 입력을 시작할 때 (입력을 허락 할지 말지 허락)

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool

 

- 유저의 입력이 시작된 시점에 호출 (시점의 작업)

func textFieldDidBeginEditing(_ textField: UITextField)

 

- 입력내용 전체를 삭제할 때(삭제 해도 되는지 허락)

func textFieldShouldClear(_ textField: UITextField) -> Bool

 

- 한글자 한글자 입력되거나 지워질 때 호출 ( 입력, 삭제를 해도 되는지 허락)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

숫자만 입력받도록

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 숫자만 입력받도록
        if Int(string) != nil || string == ""{
            return true // 숫자 입력을 허용
        }
        return false // 문자 입력을 허용하지 않음
    }

 

- 키보드의 엔터키가 눌렸을 때(다음 동작을 허락 할건지 말건지 허락)

func textFieldShouldReturn(_ textField: UITextField) -> Bool

엔터키의 기능 구현

// 엔터를 입력하면 다음 텍스트필드 or 키보드 내리는 기능 구현
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 두 텍스트 필드가 모두 입력이 되었다면 resignFirstResponder()
        if heightTextField.text != "", weightTextField.text != ""{
            weightTextField.resignFirstResponder()
            return true
        } else if heightTextField.text != ""{
            weightTextField.becomeFirstResponder()
            return true
        }
        return false
    }

 

- 유저의 입력이 끝났을 때(입력이 끝날 때 끝낼지 말지 허락)

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool

 

- 입력이 실제 끝났을 때 호출 (시점의 작업)

func textFieldDidEndEditing(_ textField: UITextField)

 

파라미터

textField: 편집 중인 텍스트 필드입니다.

range: 사용자가 변경하려는 문자의 범위입니다. 이것은 대체되거나 삭제되는 문자와 새 문자를 삽입해야 하는 위치를 결정하는 데 사용할 수 있습니다.

replacementString: 사용자가 삽입하거나 바꾸려는 문자열입니다. 이것은 입력의 유효성을 검사하거나 어떤 식으로든 텍스트를 수정하는 데 사용할 수 있습니다(예: 모든 입력을 대문자로 변환).

저작자표시 비영리 동일조건 (새창열림)
    'iOS - UIKit' 카테고리의 다른 글
    • [UIKit] UISlider
    • [UIKit] UICollectionView
    • IOS - Navigation Controller
    • UIkit - UITableView
    clamp
    clamp
    주니어 iOS개발자의 발악!!!!!!!

    티스토리툴바