Table 查看具有不同数据的自定义单元格

Table View custom cells with different data

所以,我想将不同的图像放入 tableview 单元格中,并且我有 3 个不同的文件。我已经做了一些编码,但现在我无法完成它。请查看我的代码并告诉我如何处理这场斗争,我是新手。 (卡了一整天)...这一切的重点是让 具有不同图像和两个标签的自定义单元格。

First file

class MenuCells {

private var _cellTitle: String
private var _cellDetails: String
private var _cellIcon: Array<String>

var cellTitle: String {
    return _cellTitle
}

var cellDetails: String {
    return _cellDetails
}

var cellIcon: Array<String> {
    return _cellIcon
}

init(cellTitle: String, cellDetails: String, cellIcon: Array<String>) {

    _cellTitle = cellTitle
    _cellDetails = cellDetails
    _cellIcon = cellIcon

}

func cellData() {
    _cellTitle = "x"
    _cellDetails = "y"
    _cellIcon = ["1","2","3","4"]
}

}

Second File

class MenuCell: UITableViewCell {


@IBOutlet weak var bg: UIView!
@IBOutlet weak var cellTitle: UILabel!
@IBOutlet weak var cellDetails: UILabel!
@IBOutlet weak var cellIcon: UIImageView!


override func awakeFromNib() {
    super.awakeFromNib()


}

func configureCell(menuCell: MenuCells) {

    cellTitle.text = menuCell.cellTitle
    cellDetails.text = menuCell.cellDetails
    cellIcon.image = UIImage(named: "\(menuCell.cellIcon)")

}
}

Third File (Here Im stuck, I dont know how implement the data)

import UIKit

class MenuVC: UIViewController, UITableViewDelegate, UITableViewDataSource {


@IBOutlet weak var tableMenu: UITableView!



override func viewDidLoad() {
    super.viewDidLoad()

    tableMenu.delegate = self
    tableMenu.delegate = self



}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

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


    return cell
}


}

你需要做这样的事情。

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

// create object of MenuCells file and assign your variables.Instead of creating array of images in MenuCell, create array in this file and send image as a param 1-by-1.
let myMenuCells = MenuCells(cellTitle: "Title", cellDetails: "Details", cellIcon: image) 

//By this below method set your data in your outlets. As this func is already doing so call it.
cell.configureCell(menuCell: myMenuCells)

return cell
    }

并改变

  • private var _cellIcon: Array<String>private var _cellIcon: String 因为您只需发送图像名称,然后 func configureCell 自动将图像分配给您的插座。

  • cellIcon.image = UIImage(named: "\(menuCell.cellIcon)")cellIcon.image = UIImage(named: menuCell.cellIcon)

如果故事板中有原型单元格,则可以为每个原型单元格设置一个标识符,并使用 if 语句为每个单元格单独设置代码 运行。 (所以检查标识符是否适用于单元格 A,如果是,运行 单元格 A 的设置,否则 运行 单元格 B 的设置)。