当我尝试申请" Font"在滚动tableview时,它会自动应用于其他单元格

时间:2015-07-02 06:40:17

标签: swift uitableview fonts uifont custom-cell

我有自定义的tableview。

我需要将Bold Italic(Helvetica-BoldOblique)字体设置为cell.But当它滚动tableview时它也会逐个应用于其他单元格。如何解决这个问题?

    func applyFontToTableviewCell() {

    var couIn = NSIndexPath(forRow: 2, inSection: 0)
    var couCell = colorTableView.cellForRowAtIndexPath(couIn)
    couCell?.textLabel?.font = UIFont(name: "Helvetica-BoldOblique", size: 18.0)


    }

我也在cellForRowAtIndexPath中尝试了相同的代码。但是出现了同样的问题。

先谢谢。

3 个答案:

答案 0 :(得分:2)

你必须检查条件:

if (NSIndexPath(forRow: 2, inSection: 0)){
      couCell?.textLabel?.font = UIFont(name: "Helvetica-BoldOblique", size: 18.0)
}
else{
      //set your default font
      couCell?.textLabel?.font = UIFont(name: "Helvetica", size: 18.0)
}

如果你想检查奇数,甚至那么

if yourindexpath % 2 == 0 {
}

所以,可能就像

if (NSIndexPath(forRow: indexPath.row % 2, inSection: 0)){
  couCell?.textLabel?.font = UIFont(name: "Helvetica-BoldOblique", size: 18.0)
}
else{
  //set your default font
  couCell?.textLabel?.font = UIFont(name: "Helvetica", size: 18.0)
}

答案 1 :(得分:2)

您可以像其他方式一样在替代单元格上应用粗体字体。

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let couCell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell

            let row = indexPath.row

            if row == 2 || row == 4 || row == 6 {
              couCell?.textLabel?.font = UIFont(name: "Helvetica-BoldOblique", size: 18.0)
           }
          else{
               couCell?.textLabel?.font = UIFont(name: "Helvetica", size: 18.0)
           }

            return cell
        }

希望这对你有所帮助。

答案 2 :(得分:0)

我遇到了同样的问题,并通过在willDisplayCell方法中应用字体进行了修复

override func tableView(_ tableView: UITableView, willDisplay cell:  UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row

        if row == 2 || row == 4 || row == 6 {
          cell.textLabel?.font = UIFont(name: "Helvetica-BoldOblique", size: 18.0)
       }
      else{
           cell.textLabel?.font = UIFont(name: "Helvetica", size: 18.0)
       }
    }