swift - 如何将 subview 添加到 UITableViewCell

标签 swift uitableview uibutton uitextfield subview

我正在使用表格 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/

相关文章:

ios - 如何更改 iOS 7 中的中心标签栏按钮颜色?

Swift - 如何要求 UIGestureRecognizer 函数返回值

ios - 如何设置动态 UICollectionView 单元格高度?

ios - UITableViewCell textLabel attributedText iOS7

ios - 显示YouTube channel

iphone - 如何给 UIButton 添加阴影?

ios - 以正确的方式分配回调

ios - 我使用此代码弹出一个带有“取消”和“提交”选项的文本字段,但键盘也显示。我不想显示键盘

iphone - 如何解决表格 View 中的滚动问题

c# - MonoTouch 中的自定义 UIButton 颜色