gpt4 book ai didi

swift - 如何将 subview 添加到 UITableViewCell

转载 作者:行者123 更新时间:2023-11-28 15:56:37 24 4
gpt4 key购买 nike

我正在使用表格 View 制作待办事项计划表。当用户在输入任务后按下回车键时,任务左侧应出现一个按钮。

我的 ViewController 类中的 textFieldShouldReturn 方法添加了按钮,但并不总是在屏幕的左上角。我是这样设置的:

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

self.view.addSubview(cell.cellButton)

向 View 添加一个按钮,但按钮没有出现在正确的位置,(我尝试使用 Storyboard移动位置,但它没有做任何事情)。此外,该按钮不会响应其在子类中声明的适当的点击操作。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell
cell.textField.delegate = self
...
return cell
}

感谢任何帮助。如果我不太清楚请告诉我

最佳答案

你没有捕获这一行中的正确单元格:

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! TextInputTableViewCell

您基本上是在告诉系统只给您一个单元格。您需要找出实际返回的文本字段,并获取包含该文本字段的单元格,然后将您的 subview 添加到正确的单元格中。这样做的方法是用行号标记您的文本字段。

它在第一个示例中有效,因为您在 cellForRow 中,所以您确实拥有正确的单元格。

关于swift - 如何将 subview 添加到 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com