Swift 创建新的UITableView单元格';s textField是第一个响应者
我目前有一个表格视图,其中的单元格包含一个标签和一个Swift 创建新的UITableView单元格';s textField是第一个响应者,swift,uitableview,uitextfield,Swift,Uitableview,Uitextfield,我目前有一个表格视图,其中的单元格包含一个标签和一个textfield,我还有一个+条按钮项,用于添加新的单元格 我希望在用户按下+按钮时创建新单元格,该单元格的文本字段将自动成为第一响应者 以下是创建新条目的当前代码: func newNoteline() { let entityDescription = NSEntityDescription.entity(forEntityName: "NotebookContentEntity", in: context) l
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
如果用户不点击文本字段,我就不知道如何将焦点强制到单元格中的特定文本字段。有什么想法吗?调用文本字段。方法应该满足您的要求。何时调用此函数取决于您。例如,在下面的代码中,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
}
}
您可以调用becomeFirstResponder作为文本字段的第一响应者