ios - 在表格 View 的特定单元格中创建文本字段

标签 ios swift uitableview uitextfield

我想在表格 View 的特定单元格中插入文本字段。我有一个包含 12 个字符串的数组(其中 3 个是空格)。 tableview 中的那些空白单元格,我想在其中创建一个文本字段,以便用户可以在这些空槽中键入内容。但是我无法仅在那些空白的插槽中创建文本字段。我该怎么做?

    var items = ["Apple", "Fish", "Dates", "Cereal", "Ice cream", "Lamb", "Potatoes", "Chicken", "Bread", " ", " "," "]

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cellFruit", forIndexPath: indexPath)

    if (items[indexPath.row] == " ") {
        cell.textLabel?.text = items[indexPath.row]
        let collar = UIColor.init(red: 175, green: 189, blue: 212, alpha: 0.4)
        cell.backgroundColor = collar
        return cell

    }
    else {
        cell.textLabel?.text = items[indexPath.row]
        let coL = UIColor.init(red: 59, green: 89, blue: 152, alpha: 0.2)
        cell.backgroundColor = coL
        return cell

    }

}

这是我重新加载单元格的方法。现在文本字段正在显示,但它开始显示在字符串为非空空格的单元格中。

     func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
    if (sourceIndexPath.row != destinationIndexPath.row){
        let temp = items[sourceIndexPath.row]
        items.removeAtIndex(sourceIndexPath.row)
        items.insert(temp, atIndex: destinationIndexPath.row)

    }
    tableView.reloadData()
}

最佳答案

您可以创建两个单元格(或一个单元格使用 init(style: UITableViewCellStyle, reuseIdentifier: String?)),例如单元格标识符为“default”和“wTextfield”。一个单元格默认,第二个单元格将有文本字段。如果它们不是来自 Storyboard,则在 viewDidLoad 中注册它们(如果它们来自 Storyboard,则不需要):

override func viewDidLoad()
{        
    super.viewDidLoad()
    //some setup

    tableView.registerClass(MyCell, forCellReuseIdentifier: "default")
    tableView.registerClass(MyCell, forCellReuseIdentifier: "wTextfield")
}

然后,当您在 cellForRowAtIndexPath 方法中设置您的单元格时,您可以为您选择正确的单元格:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var cellId = "default"
    if items[indexPath.row] == " " {cellId = "wTextfield"}
    let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath) as! MyCell

    //set up your cell now
    return cell
}

关于ios - 在表格 View 的特定单元格中创建文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38071294/

相关文章:

.net - MonoTouch UITableView 问题

ios - 滚动时 UITableView 奇怪的布局行为发生变化

ios - 旋转时图像尺寸发生变化

ios - 如何使用图像创建 UIAlertView

ios - 为未调用的 UIButton 添加目标

ios - 异步函数和 Firebase 与 Swift 3

ios - Swift 2.0 迁移错误

ios - 编程 slider 约束未更新

ios - 检测以查看是否启用了iPad上的蓝牙iOS 7

ios - 自定义 UITableViewCell 中的不同高度