語境
基本清單。當用戶按下“ ”時,代碼會創建一個帶有用戶可以更改的默認文本的新專案。

問題
我想在用戶按下“ ”后立即聚焦新專案,以便用戶可以輸入所需的名稱。我嘗試使用以下代碼實作此目的:
func focus() {
title.becomeFirstResponder()
title.selectAll(nil)
}
但becomeFirstResponder()總是回傳false。
我怎樣才能UITextField在我的UITableviewCell創作后集中注意力?
這是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)
}
}
uj5u.com熱心網友回復:
您可以在視圖控制器中添加一個布林值來跟蹤添加專案,即 默認值為 false 的isAddingItem,當您添加新專案時,只需將isAddingItem更新為 true。在 tableview cellForRowAt方法中檢查tableview的最后一個單元格,如果isAddingItem為 true,則選擇文本欄位的所有文本并使其成為第一回應者。
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])
if isAddingItem && indexPath.item == model.count {
// make your textfield first here and select text here
}
return cell
}
還要檢查您是否設定了文本欄位委托。
uj5u.com熱心網友回復:
好的,我發現問題了!
我使用的是 methodself.tableView(self.tableView, cellForRowAt: indexPath)而不是self.tableView.cellForRow(at: indexPath).
以下是檔案的內容:“永遠不要自己呼叫此方法。如果您想從表格中檢索單元格,請cellForRow(at:)改為呼叫表格視圖的方法。”
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/363804.html
