我正在尝试创建一个列表应用程序,并使用TableView和TextView的组合。我有一个包含数据的groups和groupsItem数组。我使用这些数组来填充tableview。
当用户点击“enter”时,我添加到数组并重新加载表。它运行良好,但问题是我无法将textView焦点转到下一个textView。下一个textView总是'nil'。我有一种感觉,因为我正在尝试在tableView重新加载时执行此操作。有任何想法吗?
class TableViewController: UITableViewController, UITextViewDelegate {
var groups = [String]()
var groupItems = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textViewDidChange(_ textView: UITextView) {
tableView.beginUpdates()
tableView.endUpdates()
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return groups[section]
}
override func numberOfSections(in tableView: UITableView) -> Int {
return groups.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupItems[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ExpandingCell
cell.textView.delegate = self
cell.textView.tag = indexPath.row
cell.textView?.text = groupItems[indexPath.section][indexPath.row]
return cell
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
// On enter add to second last item in array
groupItems[groupItems.count - 1].insert(textView.text, at: groupItems[groupItems.count - 1].count - 1)
// Reload the table to reflect the new item
tableView.reloadData()
// Try to find next responder
if let nextField = textView.viewWithTag(textView.tag + 1) as? UITextView {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textView.resignFirstResponder()
}
return false
}
return true
}
@IBAction func AddItem(_ sender: UIButton) {
groups.append("Cake")
groupItems.append([""])
tableView.reloadData()
}
}
您可能需要做两件事:
-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]
查看下一行。-[UIView layoutIfNeeded]
进行自我介绍。表格视图通常不会在reloadData
期间将子视图添加到自身,仅在布局期间。