Swift 如何将子视图添加到UITableViewCell
我正在使用表视图制作待办事项计划表。当用户在键入任务后按enter键时,任务左侧应显示一个按钮 我的ViewController类中的textFieldShouldReturn方法添加了按钮,但并不总是在屏幕的左上角。我把它设置成这样:Swift 如何将子视图添加到UITableViewCell,swift,uitableview,uibutton,uitextfield,subview,Swift,Uitableview,Uibutton,Uitextfield,Subview,我正在使用表视图制作待办事项计划表。当用户在键入任务后按enter键时,任务左侧应显示一个按钮 我的ViewController类中的textFieldShouldReturn方法添加了按钮,但并不总是在屏幕的左上角。我把它设置成这样: func textFieldShouldReturn(_ textField: UITextField) -> Bool { let cell = tableView.dequeueReusableCell(withIdentifier: "c
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell
self.view.addSubview(cell.cellButton) // puts a button in a wrong location, button doesn't respond to any action
cell.addSubview(cell.cellButton)
tableViewData.append(textField.text!)
lastItem = tableViewData.count
print(tableViewData)
print(lastItem)
self.tableView.reloadData() //update row count and array count
textField.resignFirstResponder()
return true
}
在视图中添加一个按钮,但该按钮没有显示在正确的位置,我尝试使用情节提要移动位置,但它没有任何作用。另外,该按钮不会响应其相应的单击操作,该操作在子类中声明
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell
cell.textField.delegate = self
...
return cell
}
感谢您的帮助。如果我不太清楚,请告诉我。如果您将.xib或故事板文件中的按钮对齐,然后将其隐藏,直到需要显示它,是否会更容易 您没有抓住该行中的正确单元格:
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell
你基本上是告诉系统给你一个手机。您需要找出实际返回的文本字段,并获取包含该文本字段的单元格,然后将子视图添加到正确的单元格中。方法是用行号标记文本字段
它在第一个示例中起作用,因为您位于cellForRow中,所以您的单元格是正确的 嗯,你能给出一些代码/伪代码来说明如何做到这一点吗?我只对所有行使用一个textField实例,这似乎可以很好地共享更多代码?我认为你错了,每个单元格都应该有自己的textfield实例。你可能对电池如何重复使用以及如何工作缺乏关键的理解。尝试在委托方法中放置断点,您将看到字段是不同的。
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell