,可以通过以下步骤实现:
class CustomTableViewCell: UITableViewCell {
var textField: UITextField!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
textField = UITextField()
// 进行TextField的布局设置,如frame、placeholder等
// ...
addSubview(textField)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
cellForRowAt
方法中,为每个自定义的TableViewCell子类设置一个tag,用于标识不同的TextField。func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
// 设置tag,用于标识不同的TextField
cell.textField.tag = indexPath.row
return cell
}
textFieldDidEndEditing
方法,通过tag获取对应的TableViewCell和TextField,并获取文本内容。func textFieldDidEndEditing(_ textField: UITextField) {
guard let cell = textField.superview?.superview as? CustomTableViewCell else {
return
}
let indexPath = tableView.indexPath(for: cell)
let text = textField.text ?? ""
// 处理获取到的文本内容
// ...
}
protocol CustomTableViewCellDelegate: AnyObject {
func textFieldDidChange(in cell: CustomTableViewCell, text: String)
}
class CustomTableViewCell: UITableViewCell {
weak var delegate: CustomTableViewCellDelegate?
// ...
@objc func textFieldDidChange(_ textField: UITextField) {
delegate?.textFieldDidChange(in: self, text: textField.text ?? "")
}
// 在初始化方法中为TextField添加文本变化事件
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
在UIViewController中实现CustomTableViewCellDelegate,并在代理方法中处理文本内容。
class ViewController: UIViewController, CustomTableViewCellDelegate {
// ...
func textFieldDidChange(in cell: CustomTableViewCell, text: String) {
let indexPath = tableView.indexPath(for: cell)
// 处理获取到的文本内容
// ...
}
// ...
}
通过以上步骤,你可以从自定义TableViewCell子类中的TextField获取和传递文本内容。
领取专属 10元无门槛券
手把手带您无忧上云