Swift:UITableViewCell 中 UITextField 的委托不起作用

L. *_*han 1 delegates uitableview uitextfielddelegate swift

我正在尝试将 my 的代表设置titleTF为 myUITableViewCell或 my UITableView。这就是我在班级中设置文本字段的方式UITableViewCell

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)
}
}
Run Code Online (Sandbox Code Playgroud)

这是我的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
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 5

您必须在 awakeFromNib 内调用委托(有同样的问题):

override func awakeFromNib() {
    super.awakeFromNib()
    textField.delegate = self
}
Run Code Online (Sandbox Code Playgroud)