原型UITableViewCell与其他对象(UITextField,UISwitch)

时间:2017-02-20 18:16:41

标签: ios swift xcode tableview

我正在尝试制作一个UITableView,它可以支持在其中包含不同的对象/元素。具体而言,这些元素是UITextFieldUISwitch

第一个问题:

元素没有显示出来。它们放在原型cell中,然后在我设置的class内构建。我已经确认cell设置正常,因为我可以更改每个cell上的字词,但cell中没有元素。

以下是构建我的单元格的代码:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return 1
}



public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "EmailCell")
    return cell
}

第二个问题(可能与第一个问题一起解决):

我无法访问每个UITextField或每个UISwitch中的信息。如何从存在的所有单元格中获取此信息?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您的代码存在多处问题。

对于自定义单元格,您需要实现自定义UITableViewCell子类。这是一个例子:

import UIKit    

class EmailCell: UITableViewCell {

    @IBOutlet var customTextField: UITextField!
    @IBOutlet var customSwitch: UISwitch!

}

之后,打开故事板并选择原型单元格。在Identity Inspector中将其类更改为EmailCell

enter image description here

还要确保将您的ui元素连接到之前创建的@IBOutlet。如果您需要有关@IBOutlet的帮助,请参阅this StackOverflow post

enter image description here

在下一步中,更改tableView(_:, cellForRowAt:)实施,如下所示:

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "EmailCell", for: indexPath) as! EmailCell

    // Configure your custom ui elements however you want
    cell.customTextField.text = "somestring"
    cell.customSwitch.isOn = true

    return cell
}

答案 1 :(得分:0)

确保您的单元格具有重复使用标识符并且您正在使用

tableView.dequeueReusableCell(withIdentifier: -Your cell Id- , for: indexPath) as? -Your Cell Class- 

在索引数据源方法

中的行的单元格中

接下来,您可以通过在单元格中为索引数据源方法的行执行此操作,将目标添加到单元格文本字段/开关

cell.-your switch / text field-.addTarget(self, action: #selector(valueChanged(_:)), for: .valueChanged)

并且您应该将uitableview单元格子类化以添加属性/ iboutlets

class YourTableViewCell: UITableViewCell {

  @IBOutlet weak var yourSwitch: UISwitch!

}