UIKit

[UIKit] UITextField

usia_ 2024. 7. 29. 16:49
 

[UIKit] hierarchy, 계층구조

UIKit은 'User Interface Kit'으로 사용자 인터페이스를 구성하는데 사용하는 인터페이스이다.NSObject는 대부분의 Objective-C 클래스의 루트클래스이자, Swift에서도 기반 클래스가 되며, 기본적인 객체의

usiacode.tistory.com

[NSObject - UIResponder - UIView - UIControl - UITextField]

 

 

 

UITextField는 사용자가 텍스트를 입력할 수 있는 단일 행 입력칸이다. 보통 양식이나 로그인 화면에서 사용된다.

Delegate 패턴으로 다양한 프로토콜을 추가하여 다양한 함수들을 통해 기능들을 컨트롤할 수 있다.

 

Property, Method
textfield.delegate =  self 
// 대리자 설정, 보통 뷰 컨트롤러(self)로 지정, viewDidLoad() 에 작성
//ViewController 에 프로토콜 UITextFieldDelegate 추가

textfield.placeholder = "이메일을 입력하세요." // 플레이스홀더 설정
textfield.keyboardType = .emailAddress // 키보드 타입 설정
textfield.backgroundColor = .clear
textfield.textColor = .black
textfield.tintColor = .black
textfield.autocapitalizationType = .none // 자동대문자
textfield.borderStyle = .roundedRect // 테두리 설정
textfield.clearButtonMode = .whileEditing // 클리어버튼 설정
textfield.returnKeyType = .done // 리턴키 설정
textfield.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged) 
// 값이 변할 때마다 해당 함수 호출

 

Delegate Method (보통 extension ViewController: UITextFieldDelegate{} 에 작성)
// 텍스트필드의 편집을 시작할 때 호출 (허락) 
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {  
  print("텍스트필드의 편집을 시작합니다.")
  return true
}

// 텍스트필드의 편집이 시작된 후 호출
func textFieldDidBeginEditing(_ textField: UITextField) { 
	print("텍스트필드의 편집이 시작되었습니다.")
}

// 텍스트필드의 내용이 수정될 때 호출 (허락) 
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
	print("내용이 \(string)으로 변경되었습니다.")
	if Int(string) == nil {
		return true
	} else {
		return false
  }
}

// 텍스트필드의 내용이 삭제될 때 호출
func textFieldShouldClear(_ textField: UITextField) -> Bool {  
	print("텍스트필드의 내용이 삭제되었습니다.")
	return true
}
    
// 텍스트필드의 리턴키가 눌렸을 때 호출 (엔터 -> 버튼 눌리게)    
func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
	print("텍스트필드의 리턴키가 눌렸습니다.")
	textfield.resignFirstResponder() // 키보드 내려지게 FirstResponder 해제
	return true
}
    
// 텍스트필드의 편집이 종료될 때 호출
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { 
	print("텍스트필드의 편집이 종료됩니다.")
	return true
}
    
// 텍스트필드의 편집이 종료되었을 때 호출
func textFieldDidEndEditing(_ textField: UITextField) { 
	print("텍스트필드의 편집이 종료되었습니다.")
}
    

// + 옆의 버튼이 눌렸을 때 키보드 내려가게
@IBAction func button(_ sender: UIButton) { 
	textfield.resignFirstResponder()
}

 

 

 

 

스토리보드에서 추가

'Command + Shift + L'

 

 

 

 

코드로 추가 (Delegate Method는 ViewController를 extension하여 사용)
import UIKit

class ViewController: UIViewController {
    
    private lazy var myTextField: UITextField = {
        var tf = UITextField()
        tf.frame.size.height = 48
        tf.backgroundColor = .clear
        tf.textColor = .white
        tf.tintColor = .white
        tf.autocapitalizationType = .none // 자동대문자
        tf.autocorrectionType = .no
        tf.spellCheckingType = .no
        tf.keyboardType = .emailAddress
        //tf.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged) // 값이 변할 때마다 해당 함수 호출
        view.addSubview(tf)
        //tf.keyboardType = .emailAddress // 키보드 타입 설정
        //tf.placeholder = "이메일을 입력하세요." // 플레이스홀더 설정
        //tf.borderStyle = .roundedRect // 테두리 설정
        //tf.clearButtonMode = .whileEditing // 클리어버튼 설정
        //tf.returnKeyType = .done // 리턴키 설정
        return tf
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        myTextField.delegate = self
        myTextField.becomeFirstResponder()
        myTextFieldSetup()
    }
    
    func myTextFieldSetup() {
        myTextField.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            myTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
            myTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30),
            myTextField.topAnchor.constraint(equalTo: view.topAnchor, constant: 30),
            myTextField.heightAnchor.constraint(equalToConstant: 40)
        ])
    }
    
}


extension ViewController: UITextFieldDelegate {
    // 텍스트필드의 편집을 시작할 때 호출 (허락)
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("텍스트필드의 편집을 시작합니다.")
        return true
    }
    
    // 텍스트필드의 편집이 시작된 후 호출
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("텍스트필드의 편집이 시작되었습니다.")
    }
    
    // 텍스트필드의 내용이 수정될 때 호출 (허락)
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        print("내용이 \(string)으로 변경되었습니다.")
        if Int(string) == nil {
            return true
        } else {
            return false
        }
    }
    
    // 텍스트필드의 내용이 삭제될 때 호출
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        print("텍스트필드의 내용이 삭제되었습니다.")
        return true
    }
    
    // 텍스트필드의 리턴키가 눌렸을 때 호출 (엔터 -> 버튼 눌리게)
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("텍스트필드의 리턴키가 눌렸습니다.")
        myTextField.resignFirstResponder() // 키보드 내려지게 FirstResponder 해제
        return true
    }
    
    // 텍스트필드의 편집이 종료될 때 호출
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        print("텍스트필드의 편집이 종료됩니다.")
        return true
    }
    
    // 텍스트필드의 편집이 종료되었을 때 호출
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("텍스트필드의 편집이 종료되었습니다.")
    }
    
    
    // + 옆의 버튼이 눌렸을 때 키보드 내려가게
    @IBAction func button(_ sender: UIButton) {
        myTextField.resignFirstResponder()
    }
}

 

 

 

 

'UIKit' 카테고리의 다른 글

[화면 전환] Only Code  (0) 2024.07.30
[화면 전환] Storyboard + Code  (0) 2024.07.29
[UIKit] UISlider  (0) 2024.07.29
[UIKit] UIButton  (0) 2024.07.29
[UIKit] UILabel  (0) 2024.07.29