【问题标题】:Making a new UITableView cell's textField the firstResponder将新 UITableView 单元格的 textField 设为 firstResponder
【发布时间】:2019-02-26 04:49:04
【问题描述】:

我目前有一个表格视图,其中包含一个标签和一个 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 - 使用文本字段委托或使用 tableView 委托方法 - indexPathForPreferredFocusedView.

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

【问题讨论】:

  • 可以调用文本字段的 becomeFirstResponder

标签: swift uitableview uitextfield


【解决方案1】:

致电 textField.becomeFirstResponder() method 应该可以满足您的需求。

何时调用此函数由您决定。例如在下面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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多