swift - 将新 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
。
我只是不知道如何在没有用户点击文本字段的情况下将焦点强制到单元格中的特定文本字段。有什么想法吗?
解决方案
调用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
}
}
推荐阅读
- go - golan-gin api 返回无效的 URL 转义 %
- php - 使用 PHP/HTML 在表单验证中突出显示空文本框
- javascript - 无法滚动网格直到记录结束
- bunifu - Bunifu Flat Button: Selected Property Problem (取消选择本身)
- python-3.x - Pip install 在窗口上的 docker 容器中不起作用
- swift - 在 Swift 中将 GPS 元数据写入 EXIF
- javascript - 失去地图功能的上下文
- r - R函数ggplot和lines一起不起作用,每次发送不同的警告消息
- python - sphinx 默认模板是什么?
- crystal-reports - Crystal Reports 文本旋转