TableViewController中的多个自定义单元格

时间:2015-08-28 22:13:16

标签: ios xcode swift

相当新的。我试图将3个自定义单元格填充到TableViewController中。

我已经管理(帮助)让2加载没有任何问题。这是我用于2的代码:

override func viewDidLoad() {
super.viewDidLoad()

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

}


override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath.row % 2 == 0 {
        let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell") as! FirstTableViewCell
        cell.artImageView.image = UIImage(named: "art")

        return cell

    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! SecondTableViewCell
        cell.kidsImageView.image = UIImage(named: "kids")


        return cell
    }

当我尝试添加第三行时,这就是我遇到麻烦的地方。这是我使用的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44

}


override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if indexPath.row % 3 == 0 {
        let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell") as! FirstTableViewCell
        cell.artImageView.image = UIImage(named: "art")

        return cell

    } else if {
        let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! SecondTableViewCell
        cell.kidsImageView.image = UIImage(named: "kids")


        return cell

    } else {
        let cell = tableView.dequeueReusableCellWithIdentifier("ThirdCell") as! ThirdTableViewCell
        cell.pastaImageView.image = UIImage(named: "pasta")


        return cell
    }

}

任何帮助都会很棒。格拉西亚斯。

1 个答案:

答案 0 :(得分:1)

您的问题始于此行

  if indexPath.row % 3 == 0 {

如果你真的想要细胞1,2,3,你可以这样做:

 if indexPath.row  == 0 {
    let cell = tableView.dequeueReusableCellWithIdentifier("FirstCell") as! FirstTableViewCell
    cell.artImageView.image = UIImage(named: "art")

    return cell

} else if indexPath.row == 1 {
    let cell = tableView.dequeueReusableCellWithIdentifier("SecondCell") as! SecondTableViewCell
    cell.kidsImageView.image = UIImage(named: "kids")


    return cell

} else if indexPath.row == 2 {
    let cell = tableView.dequeueReusableCellWithIdentifier("ThirdCell") as! ThirdTableViewCell
    cell.pastaImageView.image = UIImage(named: "pasta")


    return cell
}

使用indexPath.row % 3 == 0进行模数运算,因此它会给你" FirstCell"仅当indexPath.row / 3等于整数时。然后你有一个else if没有测试,所以它被调用所有其他行。最后,您的else永远不会被调用。