728x90
커스텀 내용
- 오른쪽 버튼에 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
'IOS > IOS 응용' 카테고리의 다른 글
[iOS - swift] UITextField 포맷 (핸드폰 번호, 이메일, 카드 번호) - AnyFormatKit 사용 (0) | 2021.05.03 |
---|