【发布时间】:2021-11-16 11:09:58
【问题描述】:
上下文
基本列表。当用户按下“+”时,代码会创建一个带有用户可以更改的默认文本的新项目。
问题
我想在用户按下“+”后立即关注新项目,以便用户可以输入所需的名称。我尝试用这段代码来实现这一点:
func focus() {
title.becomeFirstResponder()
title.selectAll(nil)
}
但是becomeFirstResponder() 总是返回false。
创建后如何在UITableviewCell 中将焦点放在UITextField 上?
这里是UITableViewController的完整代码供参考:
import UIKit
class ViewController: UITableViewController{
var model: [String] = ["Existing item"]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemUI", for: indexPath) as! ItemUI
cell.update(with: model[indexPath.item])
return cell
}
@IBAction func createItem(_ sender: UIBarButtonItem) {
let indexPath = IndexPath(item: model.count, section: 0)
model.append("new item")
tableView.reloadData()
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
let cell = self.tableView(self.tableView, cellForRowAt: indexPath) as! ItemUI
cell.focus()
}
}
}
class ItemUI: UITableViewCell{
@IBOutlet var title: UITextField!
func update(with: String) {
title.text = with
}
func focus() {
title.becomeFirstResponder()
title.selectAll(nil)
}
}
【问题讨论】:
标签: swift uitableview uikit uitextfield becomefirstresponder