Swift - TableView,将偶数行的字体更改为粗体

Swift - TableView, change font of even rows to bold

我有一个 table 视图,我想更改偶数行的字体,这是我的代码:

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
}

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

请记住,table 视图 重复使用 单元格。这就是为什么您从名为 dequeue<b>Reusable</b>CellWithIdentifier(_: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 row % 2 == 0 以在奇数行中使用时将单元格设置回正常字体。