如何将子视图添加到UITableViewCell

时间:2017-01-13 20:39:29

标签: swift uitableview uibutton uitextfield subview

我正在使用表格视图制作待办事项计划程序。当用户在输入任务后按Enter键时,任务左侧会出现一个按钮。

我的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)

在视图中添加了一个按钮,但按钮没有出现在正确的位置,(我尝试使用故事板移动位置,但它没有做任何事情)。此外,该按钮不会响应其在子类中声明的相应单击操作。

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

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

2 个答案:

答案 0 :(得分:1)

你没有在这一行中抓住正确的单元格:

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

你基本上告诉系统只给你一个单元格。您需要确定实际返回的文本字段,并抓取包含该文本字段的单元格,然后将子视图添加到右侧单元格。这样做的方法是使用行号标记textFields。

它适用于第一个示例,因为您位于cellForRow中,因此您拥有正确的单元格。

答案 1 :(得分:0)

如果您将.xib或storyboard文件中的按钮对齐,然后将其隐藏起来直到您需要它出现,会更容易吗?

相关问题