84 lines
2.2 KiB
Swift
84 lines
2.2 KiB
Swift
//
|
||
// LoginTextField.swift
|
||
// suixinkan
|
||
//
|
||
|
||
import SnapKit
|
||
import UIKit
|
||
|
||
/// 登录页账号输入框,对应 Android `PhoneInputField`。
|
||
final class LoginTextField: UIView {
|
||
|
||
private let textField = UITextField()
|
||
|
||
var text: String {
|
||
get { textField.text ?? "" }
|
||
set { textField.text = newValue }
|
||
}
|
||
|
||
var onTextChange: ((String) -> Void)?
|
||
var onReturnKey: (() -> Void)?
|
||
|
||
init(placeholder: String) {
|
||
super.init(frame: .zero)
|
||
setupUI(placeholder: placeholder)
|
||
setupConstraints()
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) {
|
||
fatalError("init(coder:) has not been implemented")
|
||
}
|
||
|
||
@discardableResult
|
||
override func becomeFirstResponder() -> Bool {
|
||
textField.becomeFirstResponder()
|
||
}
|
||
|
||
private func setupUI(placeholder: String) {
|
||
backgroundColor = AppColor.inputBackground
|
||
layer.cornerRadius = 12
|
||
clipsToBounds = true
|
||
|
||
textField.font = .systemFont(ofSize: 14)
|
||
textField.textColor = AppColor.text333
|
||
textField.autocapitalizationType = .none
|
||
textField.autocorrectionType = .no
|
||
textField.returnKeyType = .next
|
||
textField.clearButtonMode = .whileEditing
|
||
textField.delegate = self
|
||
|
||
let attributes: [NSAttributedString.Key: Any] = [
|
||
.foregroundColor: AppColor.placeholder,
|
||
.font: UIFont.systemFont(ofSize: 14),
|
||
]
|
||
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)
|
||
|
||
textField.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
|
||
addSubview(textField)
|
||
}
|
||
|
||
private func setupConstraints() {
|
||
snp.makeConstraints { make in
|
||
make.height.equalTo(46)
|
||
}
|
||
|
||
textField.snp.makeConstraints { make in
|
||
make.leading.trailing.equalToSuperview().inset(16)
|
||
make.centerY.equalToSuperview()
|
||
}
|
||
}
|
||
|
||
@objc private func textDidChange() {
|
||
onTextChange?(text)
|
||
}
|
||
}
|
||
|
||
extension LoginTextField: UITextFieldDelegate {
|
||
|
||
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||
onReturnKey?()
|
||
return true
|
||
}
|
||
}
|