I have two UITextFields in UITableViewCell, I want to check when the secondTextField
resignFromFirstResponder
and both firstTextField
and secondTextField
empty, It will show a warning label. Please take a look at my code below.
import Foundation
import UIKit
import SnapKit
class TwoTextInputTableViewCell: UITableViewCell {
let firstTextField = UITextField()
let secondTextField = UITextField()
let stackView = UIStackView().then {
$0.axis = .horizontal
$0.distribution = .fillEqually
$0.spacing = 15
}
let warningLabel = UILabel().then {
$0.isHidden = true
$0.addCharacterSpacing(-0.1)
$0.font = .systemFont(ofSize: 12)
$0.textColor = UIColor.CommonColor.salmonColor
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubviews(stackView, warningLabel)
stackView.addArrangedSubview(firstTextField)
stackView.addArrangedSubview(secondTextField)
stackView.snp.makeConstraints {
$0.left.equalToSuperview().offset(24)
$0.right.equalToSuperview().offset(-24)
$0.top.equalToSuperview().offset(12)
$0.height.equalTo(56)
}
warningLabel.snp.makeConstraints {
$0.top.equalTo(stackView.snp.bottom).offset(12)
$0.height.equalTo(16)
$0.left.right.equalTo(stackView)
}
}
}
Once it resign, I want to make warningLabel.isHidden = false
and reload tableView height, but how to do it? Any answer is appreciated! Thanks
CodePudding user response:
you can easily achive it by using textfield delegate
confirm to delegates first
let firstTextField = UITextField()
let secondTextField = UITextField()
firstTextField.delegate = self
secondTextField.delegate = self
observe for textFieldDidEditing Delegate
extension TwoTextInputTableViewCell : UITextFieldDelegate{
func textFieldDidEndEditing(textField: UITextField) {
if textField == firstTextField {
//first textfield resignFromFirstResponder
}else if textField == secondTextField{
//second textfield resignFromFirstResponder
}
}
}