我是新来iOS开发,我想创建自定义tableViewCells,但我有一个问题。我有3个部分为我的tableViewCell和一个数组。当我尝试将值分配给UITableView, cellForRowAt
的单元格时,它从每个部分的顶部开始数组。 这里是我的代码:自定义tableViewCell
import Foundation
import UIKit
struct cellData {
let cell : Int!
let text : String!
}
class SettingsTableViewCell : UITableViewController{
var arrayOfCellData = [cellData]()
override func viewDidLoad() {
arrayOfCellData = [cellData(cell : 1, text : "تغییر رنگ دکمه تنظیمات"),
cellData(cell : 2, text : "تغییر تصویر پشت زمینه"),
cellData(cell : 1, text : "تغییر رنگ قلم"),
cellData(cell : 2, text : "اعلانات"),
cellData(cell : 2, text : "صداها"),
cellData(cell : 2, text : "زبان"),
cellData(cell : 2, text : "بازگشت به حالت پیش فرض"),
cellData(cell : 2, text : "سوالات متداول")]
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return 3
}
else if section == 1{
return 4
}
else if section == 2{
return 1
}
return arrayOfCellData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if arrayOfCellData[indexPath.row].cell == 1{
let cell = Bundle.main.loadNibNamed("TableViewCell_Type1", owner: self, options: nil)?.first as! TableViewCell_Type1
cell.cellName_1.text = arrayOfCellData[indexPath.row].text
return cell
}
else if arrayOfCellData[indexPath.row].cell == 2{
let cell = Bundle.main.loadNibNamed("TableViewCell_Type2", owner: self, options: nil)?.first as! TableViewCell_Type2
cell.cellName_2.text = arrayOfCellData[indexPath.row].text
return cell
}
else{
let cell = Bundle.main.loadNibNamed("TableViewCell_Type1", owner: self, options: nil)?.first as! TableViewCell_Type1
cell.cellName_1.text = arrayOfCellData[indexPath.row].text
return cell
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0{
return "تنظیمات رنگ\n"
}
else if section == 1{
return "تنظیمات سیستم\n"
}
else if section == 2{
return "پشتیبانی\n"
}
return ""
}
}
不要使用像“Bundle.main.loadNibNamed”这样的旧编码方式,而应使用“registerNib”来帮助您创建单元格。另外,你可以发布你的问题的屏幕截图吗? – Satyam
在'cellForRowAtIndexPath'中,您只考虑索引路径的行。因此,每个部分显示数组顶部的相同对象。此外,你可以在Interface Builder中设计多个自定义单元格(我猜是自Xcode 6以来),不需要额外的笔尖。最后不要硬编码'numberOfRows'。用嵌套数组或其他东西创建一个合适的模型,以便始终使用'count'属性。 – vadian
您不能只考虑'indexPath.row',根据'indexPath.section'和'indexPath.row'计算数组索引。然后你会从数组中得到确切的元素。 –