2017-08-14 25 views
1

我正在實施UITableView來填充人員的聯繫人姓名。我已經實現了幾乎所有的東西。當部分包含空行時刪除UITableHeader標題

我需要刪除其行已被用戶刪除並且不包含任何其他行的節的節標題標題。有沒有辦法做到這一點。當index.item讓我崩潰時,簡單地從標題數組中刪除值。它的任何想法..

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 

     return sortedUniqueFirstLetters[section] 
    } 

    func numberOfSections(in tableView: UITableView) -> Int { 

     return sections.count 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return sections[section].count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TableViewCell 
     cell.account = sections[indexPath.section][indexPath.row] 
     return cell 
    } 

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return 80 
    } 

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){ 
     view.tintColor = UIColor.setColor(Red: 223, Green: 220, Blue: 224, Alpha: 1) 
     let header = view as! UITableViewHeaderFooterView 
     header.textLabel?.textColor = UIColor.white 
    } 

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
     return true; 
    } 

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete{ 
      ***if indexPath.item == 0{ //Trying to update title array when a section is empty 
       sortedUniqueFirstLetters.remove(at: indexPath.section) //Index out of range error here. 
      }*** 
      sections[indexPath.section].remove(at: indexPath.item) 
      tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.middle); 
     } 
    } 
+0

我不知道這是最好的解決方案,但我會做的是調用reloadtable。這將召回所有代表的表格和功能'tableViewtitleForHeaderInSection'我會檢查一節是否沒有行,然後爲該節放置一個空頭。 –

+0

我試過這兩種方法,但似乎不是正確的想法,因爲它被稱爲多次,雖然該部分不是空的 – Bikram

回答

0

你也應該使用heightForHeaderInSction以及與titleForHEaderInSction方法一起。讓我知道如果下面的代碼適合你:

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    let numberOfRows = tableView.numberOfRows(inSection: section) 
    if numberOfRows == 0 { 
     return "" 
    }else{ 
     return sortedUniqueFirstLetters[section] 
    } 

} 

func tableView (tableView:UITableView , heightForHeaderInSection section:Int) -> Float { 
    let title = self.tableView(tableView, titleForHeaderInSection: section) 
    if (title == "") { 
     return 0.0 
    } 
    return 80.0 
} 
+0

而不是實現'heightForHeaderInSection'(它真的只需要與'viewForHeaderInSection'一起使用),只需從'titleForHeaderInSection'返回'nil'而不是空字符串。 – rmaddy

+0

我在numberOfRows == 0處得到一個crahs。 – Bikram