Swift-表格视图,将偶数行的字体更改为粗体

Swift-表格视图,将偶数行的字体更改为粗体,swift,tableview,tablecell,Swift,Tableview,Tablecell,我有一个tableview,我想更改偶数行的字体,下面是我的代码: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "ProductListTableViewCell" let cell = tableView.dequeueReusableCellWithIdentif

我有一个tableview,我想更改偶数行的字体,下面是我的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "ProductListTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ProductListTableViewCell

    let product = productList[indexPath.row]

    cell.productName.text = product.name
    cell.productPrice.text = "\(product.price) manat"

    if(indexPath.row % 2 == 0) {
        cell.productName.font = UIFont.boldSystemFontOfSize(13.0)
        cell.productPrice.font = UIFont.boldSystemFontOfSize(13.0)
    }
    return cell
}

当我运行代码时,开始时一切正常,当我滚动表格视图时,屏幕上出现的所有新行都变为粗体,包括偶数行和旧行。我做错了什么?

记住,表视图重用了单元格。这就是为什么要从名为
dequeueReusableCellWithIdentifier(\uxAE:forIndexPath:)
的方法中获取它们

如果是偶数行,则将字体设置为粗体;如果是奇数行,则不会将字体设置为正常。如果该单元格以前用于偶数行,而现在用于奇数行,则仍使用粗体字体

let weight = (indexPath.row % 2 == 0) ? UIFontWeightBold : UIFontWeightRegular
let font = UIFont.systemFontOfSize(13, weight: weight)
cell.productName.font = font
cell.productPrice.font = font

请记住,表视图重用单元格。这就是为什么要从名为
dequeueReusableCellWithIdentifier(\uxAE:forIndexPath:)
的方法中获取它们

如果是偶数行,则将字体设置为粗体;如果是奇数行,则不会将字体设置为正常。如果该单元格以前用于偶数行,而现在用于奇数行,则仍使用粗体字体

let weight = (indexPath.row % 2 == 0) ? UIFontWeightBold : UIFontWeightRegular
let font = UIFont.systemFontOfSize(13, weight: weight)
cell.productName.font = font
cell.productPrice.font = font

可重复使用的单元格都设置为粗体。将else添加到if行%2==0,以便在奇数行中使用单元格时将其设置回正常字体。

您的可重用单元格都设置为粗体。在if行%2==0中添加一个else,以便在奇数行中使用该单元格时将其设置为正常字体。

感谢您的回复,该操作已成功。我不得不把奇怪的几排牙缝排好以便回答,它起作用了。我必须为回复设置奇数行toothanks,正如您所说,我必须为回复设置奇数行toothanks的正常字体,正如您所说,我也必须为奇数行设置正常字体