cellForRowAtIndexPath问题

时间:2015-08-29 20:24:17

标签: ios swift uitableview

我的应用程序目前有一个包含3个不同单元格的tableview,每个单元格都有自己独立的自定义单元格。在我的type(binary)存根方法中,我有以下代码:

cellForRowAtIndexPath

我在func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 1 { let directionsCell = YelpInfoTableview.dequeueReusableCellWithIdentifier("YelpInfoDirectionCell", forIndexPath: indexPath) as! YelpInfoDirectionCell directionsCell.business = currentBusiness return directionsCell } else if indexPath.row == 2 { let contactCell = YelpInfoTableview.dequeueReusableCellWithIdentifier("YelpInfoContactCell", forIndexPath: indexPath) as! YelpInfoContactCell contactCell.business = currentBusiness return contactCell } else { let infoCell = YelpInfoTableview.dequeueReusableCellWithIdentifier("YelpInfoInfoCell", forIndexPath: indexPath) as! YelpInfoInfoCell infoCell.business = currentBusiness return infoCell } } 方法中设置了dataSourcedelegate,所有这些都位于我的Detail VC中。我在stubbed方法中设置了一个断点,问题是它会在触发Detail VC的VC后立即触及该断点,因此会进入viewDidLoad else语句。

如果用户按下第一个单元格,它会加载单元格A,第二单元格,单元格B等,我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

您需要做的是:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var businessMock: Business = Business(dictionary: currentBusiness)

        if indexPath.row == 0 {
            let directionsCell = YelpInfoTableview.dequeueReusableCellWithIdentifier("YelpInfoDirectionCell", forIndexPath: indexPath) as! YelpInfoDirectionCell
//            directionsCell.business = currentBusiness
            directionsCell.business = businessMock

            return directionsCell

        } else if indexPath.row == 1 {
            let contactCell = YelpInfoTableview.dequeueReusableCellWithIdentifier("YelpInfoContactCell", forIndexPath: indexPath) as! YelpInfoContactCell
            contactCell.business = businessMock
            return contactCell

        } else {
            let infoCell = YelpInfoTableview.dequeueReusableCellWithIdentifier("YelpInfoInfoCell", forIndexPath: indexPath) as! YelpInfoInfoCell
            infoCell.business = businessMock
            return infoCell
        }
    }

您必须先创建业务对象。此外,indexPath从0开始,因此从0开始。

答案 1 :(得分:1)

索引在Swift中基于0。第一个单元格是索引0,第二个单元格具有索引1,第三个单元格具有索引2,等等。如果您希望第一行符合第一个if子句,则应该查找indexPath.row == 0而不是indexPath.row == 1