【问题标题】:Swift: Delegate of UITextField in UITableViewCell does not workSwift:UITableViewCell 中 UITextField 的代表不起作用
【发布时间】:2023-03-25 15:34:01
【问题描述】:

我正在尝试将我的titleTF 的代表设置为我的UITableViewCell 或我的UITableView。这就是我在 UITableViewCell 类中设置 textField 的方式。

class AddAppointmentTableViewCell: UITableViewCell, UITextFieldDelegate, UITextViewDelegate {
var view = UIView()
var titleTF = UITextField()

func addTitle() -> UIView {
    view = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height:
        NSAttributedString(string: "Enter Title", attributes: [.font: UIFont.boldSystemFont(ofSize: 24),
                                                               .foregroundColor: UIColor.lightGray]).size().height+30))

    titleTF.translatesAutoresizingMaskIntoConstraints = false
    titleTF.textAlignment = .left
    titleTF.delegate = self
    titleTF.attributedText = NSAttributedString(string: "Enter Title", attributes: [.font: UIFont.boldSystemFont(ofSize: 24),
                                                                                    .foregroundColor: UIColor.lightGray])
    titleTF.inputAccessoryView = toolBar
    view.addSubview(titleTF)
    titleTF.topAnchor.constraint(equalTo: view.topAnchor, constant: 15).isActive = true
    titleTF.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -15).isActive = true
    titleTF.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 15).isActive = true
    titleTF.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15)
    return view
}

func textFieldDidEndEditing(_ textField: UITextField) {
    print("textFieldDidEndEditing")
}

override func draw(_ rect: CGRect) {
    addSubview(view)
}
}

这是在我的UITableView 类中:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return rows.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return rows[indexPath.row].frame.height
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddAppointmentTableViewCell
    cell.view = rows[indexPath.row]
    return cell
}

rows 等于[cell.addTitle(), cell.addNote()]

我不明白为什么我的UITableViewCell 中的textFieldDidBeginEditing 方法没有被调用。

【问题讨论】:

  • 显示你的AddAppointmentTableViewCell
  • 你到底想看什么?
  • 您的表格视图单元格和textFieldDidBeginEditing 方法
  • 这就是您所需要的一切吗?
  • "titleTF.delegate = self" 甚至没有人知道 titleTF 是在哪里以及如何定义的。

标签: swift uitableview delegates uitextfielddelegate


【解决方案1】:

您必须在 awakeFromNib 中调用委托(遇到同样的问题):

override func awakeFromNib() {
    super.awakeFromNib()
    textField.delegate = self
}

【讨论】:

    【解决方案2】:

    你需要添加这一行

    {

    textField.delegate = self

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多