首页 > 解决方案 > 将新 UITableView 单元格的 textField 设为 firstResponder

问题描述

我目前有一个表格视图,其中包含一个标签和一个单元格textfield,我还有一个添加新单元格的 + 栏按钮项。

我希望完成的是当用户按下 + 按钮时,新单元格被创建并且该单元格的文本字段将自动成为第一响应者。

以下是我当前用于创建新条目的代码:

func newNoteline() {
    let entityDescription = NSEntityDescription.entity(forEntityName: "NotebookContentEntity", in: context)
    
    let item = NotebookContentEntity(entity: entityDescription!, insertInto: context)
    
    item.notebookEntry = ""
    item.timeOfEntry = timeOutlet.text
    
    do {
        
        try context.save()
    } catch {
        print(error)
        return
    }
    loadNotelines()
}

我已经想到了几种尝试解决这个问题的方法,但没有太多运气让它们工作,包括.tag在文本字段上使用 a ——使用文本字段委托或使用tableView委托方法—— indexPathForPreferredFocusedView

我只是不知道如何在没有用户点击文本字段的情况下将焦点强制到单元格中的特定文本字段。有什么想法吗?

标签: swiftuitableviewuitextfield

解决方案


调用textField.becomeFirstResponder() 方法应该做你正在寻找的。

何时调用此函数取决于您。例如,在下面的代码中,cellForRowAt我检查了该值是否为空,然后将当前文本字段设为第一响应者。

class Test: UIViewController{
    
    var myView: TestView{return view as! TestView}
    unowned var tableView: UITableView {return myView.tableView}
    unowned var button: UIButton {return myView.button}
    
    var list = [String]()
    
    override func loadView() {
        view = TestView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        for i in 1...10{
            list.append("Test \(i)")
        }
        tableView.dataSource = self
        button.addTarget(self, action: #selector(didSelect(_:)), for: .touchUpInside)
    }
    
    @objc func didSelect(_ sender: UIButton){
        let indexPath = IndexPath(row: list.count, section: 0)
        list.append("")
        tableView.insertRows(at: [indexPath], with: .automatic)
        tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
}

extension Test: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TestViewCell", for: indexPath) as! TestViewCell
        let value = list[indexPath.row]
        cell.textField.text = value
        if value.isEmpty{
            cell.textField.becomeFirstResponder()
        }
        return cell
    }
}

推荐阅读