我试图使用自定义单元格在tableview上显示textfield。我认为我已经正确设置了委托协议,但加载时,tableview不会显示textfield。我在customcell中添加了一个textfield,将类设置为customcell,并将标识符更改为“Cell”,但我不确定还缺少什么。
带有tableview的视图控制器:
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Hello")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.cellDelegate = self
cell.contentView.bringSubview(toFront: cell.textField)
cell.textField.delegate = self as? UITextFieldDelegate
cell.textField.text = "Test"
return cell
}
func didPressTextField(indexPath: IndexPath) {
print("textfield was tapped")
}
protocol CustomCellDelegate : class {
func didPressTextField(indexPath: IndexPath)
}
class CustomCell: UITableViewCell {
weak var cellDelegate: CustomCellDelegate?
var indexPath: IndexPath!
override func awakeFromNib() {
super.awakeFromNib()
self.cellDelegate = nil
// Initialization code
}
@IBOutlet weak var textField: UITextField!
@IBAction func textFieldWasTapped(_ sender: UITextField) {
self.cellDelegate?.didPressTextField(indexPath: indexPath)
}