简体   繁体   中英

conditional override func - swift

I'm working with UILocalizedIndexedCollation and UISearchDisplayController and I like to implement a conditional that only apply a override func if user isn't using SerachBar.

Here is the code that override a func tableView to show Collation, but how can I bypass this code if user is in Search Bar?

override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    return self.collation.sectionForSectionIndexTitleAtIndex(index)
}

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

    if !self.sections[section].users.isEmpty {
        return self.collation.sectionTitles[section] as String
    }
    return ""
}

displayed to the right of the `UITableView` */
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject] {
    return self.collation.sectionIndexTitles
}

You're not going to be able to conditionally override a method, the normal approach is to override the method and call super if you don't need the override:

override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    if showingSearch {
        return self.collation.sectionForSectionIndexTitleAtIndex(index)
    }
    else {
        return super.tableView(tableView, sectionForSectionIndexTitle:title atIndex:Index)
    }
}

finlally my code looks like this:

/* section headers appear above each `UITableView` section */
    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String {
    // do not display empty `Section`s
    if self.sections[section].users.isEmpty || tableView == self.searchDisplayController!.searchResultsTableView {
        return ""
    } else {
        return self.collation.sectionTitles[section] as String
    }
}

/* section index titles displayed to the right of the `UITableView` */
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject] {
    if tableView == self.searchDisplayController!.searchResultsTableView {
        return tableView.visibleCells()
    } else {
        return self.collation.sectionIndexTitles
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM