Last active
May 13, 2021 05:26
-
-
Save kyungpyoda/77bebc27433d76ff263c9ee193e5e9e8 to your computer and use it in GitHub Desktop.
인증번호(OneTime Code) 입력 뷰
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// OneTimeCodeTextField.swift | |
// | |
// Created by 홍경표 on 2021/05/13. | |
// | |
import UIKit | |
final class OneTimeCodeTextField: UITextField { | |
let slotCount: Int | |
private var digitLabels: [UILabel] = [] | |
init(slotCount: Int) { | |
self.slotCount = slotCount | |
super.init(frame: .zero) | |
configure() | |
} | |
required init?(coder: NSCoder) { | |
fatalError("NO WAY") | |
} | |
private func configure() { | |
self.tintColor = .clear | |
self.textColor = .clear | |
self.textAlignment = .center | |
self.keyboardType = .numberPad | |
if #available(iOS 12.0, *) { | |
self.textContentType = .oneTimeCode | |
} | |
self.addTarget(self, action: #selector(textDidChange), for: .editingChanged) | |
let tapRecognizer = UITapGestureRecognizer() | |
tapRecognizer.addTarget(self, action: #selector(becomeFirstResponder)) | |
self.addGestureRecognizer(tapRecognizer) | |
let labelsStackView = UIStackView().then { | |
$0.axis = .horizontal | |
$0.distribution = .fillEqually | |
$0.alignment = .fill | |
$0.spacing = 8 | |
} | |
for _ in 0..<slotCount { | |
let label = UILabel().then { | |
$0.textAlignment = .center | |
$0.font = .preferredFont(forTextStyle: .largeTitle) | |
$0.adjustsFontSizeToFitWidth = true | |
$0.text = " " | |
} | |
labelsStackView.addArrangedSubview(label) | |
digitLabels.append(label) | |
} | |
self.addSubview(labelsStackView) | |
labelsStackView.snp.makeConstraints { | |
$0.edges.equalToSuperview() | |
} | |
for i in 0..<slotCount { | |
let bottomLine = UIView() | |
bottomLine.backgroundColor = UIColor(named: "c006") | |
digitLabels[i].addSubview(bottomLine) | |
bottomLine.snp.makeConstraints { | |
$0.height.equalTo(2) | |
$0.leading.trailing.bottom.equalToSuperview() | |
} | |
} | |
} | |
@objc private func textDidChange() { | |
guard let text = self.text else { return } | |
guard text.count <= slotCount else { | |
self.text = text.prefix(slotCount).description | |
return | |
} | |
for i in 0..<slotCount { | |
if i < text.count { | |
digitLabels[i].text = String(text[text.index(text.startIndex, offsetBy: i)]) | |
} else { | |
digitLabels[i].text = " " | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment