Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] 비밀번호 입력창 커스텀 textField 본문

iOS 응용 (swift)

[iOS - swift] 비밀번호 입력창 커스텀 textField

jake-kim 2021. 1. 7. 22:04

커스텀 내용

  • 오른쪽 버튼에 mask버튼 존재
  • mask버튼 탭 시 입력 값 mask
  • 텍스트 필드 객체.setupValidStatus() or 객체.setupInvalidStatus()를 실행하여 텍스트 색깔 변경 가능
  • 객체.setupInvalidStatus()호출 후 delete하면 입력값 모두 삭제되는 기능

코드 내용

import UIKit
import RxSwift
import RxCocoa

@IBDesignable
class PasswordTextField: UITextField {

    enum CurrentPasswordInputStatus {
        case invalidPassword
        case validPassword
    }

    private var rightButton: UIButton!
    private let bag = DisposeBag()
    private var currentPasswordInputStatus: CurrentPasswordInputStatus = .invalidPassword
    let textResetEvent = PublishSubject<Void>()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        delegate = self
        rightButton = UIButton()
        rightButton.contentMode = .scaleAspectFit
        rightButton.setImage(UIImage(named: "open_eye"), for: .normal)
        rightView = rightButton
        rightViewMode = .always
        leftViewMode = .never

        rightButton.rx.tap.asDriver{ _ in .never() }
            .drive(onNext: { [weak self] in
                self?.updateCurrentStatus()
            }).disposed(by: bag)
    }

    private func updateCurrentStatus() {
        isSecureTextEntry.toggle()
        if isSecureTextEntry {
            rightButton.setImage(UIImage(named: "open_eye"), for: .normal)
        } else {
            rightButton.setImage(UIImage(named: "close_eye"), for: .normal)
        }
    }

    // MARK: - Public

    public func setupValidStatus() {
        textColor = .black
        currentPasswordInputStatus = .validPassword
    }

    public func setupInvalidStatus() {
        textColor = .red
        currentPasswordInputStatus = .invalidPassword
    }
}

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

        if string.isEmpty, currentPasswordInputStatus == .invalidPassword {
            textField.text = ""
            setupValidStatus()
            textResetEvent.onNext(())
            return false
        }
        return true
    }
}

* source code: github.com/JK0369/Custom_password_TextField

Comments