向 searchBar 添加索引

Add an Index to a searchBar

需要帮助来更正此代码。
我有一个带有餐厅名称和地址的核心数据应用程序,有一个搜索栏,它正在运行。我要添加的是一个 Index 和一个 IndexTitle,如下图(箭头)所示。
我们非常欢迎任何帮助。提前致谢。

import UIKit
import CoreData

class DictionaryTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchResultsUpdating
{
    var searchController:UISearchController!
    var searchResults:[Dictionary] = []

    private var dictionaryItems:[Dictionary] = []
    var fetchResultController:NSFetchedResultsController!

    override func viewDidLoad() {
        super.viewDidLoad()

    if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {

            let fetchRequest = NSFetchRequest(entityName: "DictionaryEntity")
            do {
                dictionaryItems = try managedObjectContext.executeFetchRequest(fetchRequest) as! [Dictionary]
            } catch {
                print("Failed to retrieve record")
                print(error)
            }
        }

    searchController = UISearchController(searchResultsController: nil)
        tableView.tableHeaderView = searchController.searchBar
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false

           tableView.estimatedRowHeight = 30.0
        tableView.rowHeight = UITableViewAutomaticDimension
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
}

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 26
    }

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

        if searchController.active {
            return searchResults.count
        } else {
            return dictionaryItems.count
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DictionaryTableViewCell

        // Configure the cell...
        cell.wordLabel.text = dictionaryItems[indexPath.row].word
        cell.definitionSmallLabel.text = dictionaryItems[indexPath.row].definition

    let dictionary = (searchController.active) ? searchResults[indexPath.row]: dictionaryItems[indexPath.row]

        // Configure the cell...
        cell.wordLabel.text = dictionary.word
        cell.definitionSmallLabel.text = dictionary.definition
        return cell
    }
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
    {
        return "dictionaryItems\(section)"
    }

    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {

           if searchController.active{
            return false
        }else{
            return true
        }
    }


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showDictionaryDetail" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let destinationController = segue.destinationViewController as! DictionaryDetailViewController
                destinationController.dictionary = (searchController.active) ? searchResults[indexPath.row] : dictionaryItems[indexPath.row]
                searchController.active = false
            }
        }
    }

        func updateSearchResultsForSearchController(searchController:
            UISearchController) {
                if let searchText = searchController.searchBar.text {
                    filterContentForSearchText(searchText)
                    tableView.reloadData()
                }
        }

        func filterContentForSearchText(searchText: String) {
            searchResults = dictionaryItems.filter({ (dictionary:Dictionary) -> Bool in
                let wordMatch = dictionary.word!.rangeOfString(searchText, options:
                    NSStringCompareOptions.CaseInsensitiveSearch)
                return wordMatch != nil
            })
        }
}



我想在 table 视图中添加的是索引(左侧的箭头)和索引标题(右侧的箭头)。

您在 titleForHeaderInSection

的覆盖函数中有拼写错误

这里是更正的,注意tableView中的v是大写:(复制粘贴我的代码)

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

}

我建议使用 Xcode 的 auto-complete 功能。这样,您就不会陷入这样的隐患。

更新: 您还需要提供这两种方法才能查看章节 header 和章节索引标题。

override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return ["A", "B", "C"]
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "A title for section: \(section)"
}

试试下面的代码:

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 9
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 9
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    // Configure the cell...
    cell.textLabel?.text = "\(indexPath.section+1)\(indexPath.row+1)"

    return cell
}

override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return ["A", "C", "B"]
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "SECTION \(section+1)"
}

}

一种方法是在 NSFetchedResultsController 上使用 built-in 属性。其中最重要的部分是设置 sectionNameKeyPath(应该是包含标题的托管 object 属性)。

private var frc: NSFetchedResultsController? = nil
private lazy var fetchedResultsController:NSFetchedResultsController = {

        if self.frc != nil {
            return self.frc!
        }
        //grab your managed object context
        let moc = dbStore.sharedInstance.managedObjectContext


        let fetchRequest = NSFetchRequest(entityName: "Transaction")
        fetchRequest.fetchBatchSize = 30
        fetchRequest.resultType = NSFetchRequestResultType.ManagedObjectResultType
        let sortDescriptorByTimeStamp =  NSSortDescriptor(key: "timeStamp", ascending: true)
        fetchRequest.sortDescriptors = [sortDescriptorByTimeStamp]

        //in-memory cache when cachename is nil, delegate is non-nil
        //note the sectionNameKeyPath requires that I have a related category object with the categoryName attribute on my Transaction managed object
        let nfrc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: "category.categoryName", cacheName: nil)

        self.frc = nfrc
        do
        {
            try self.frc!.performFetch()
        } catch let e as NSError {
            fatalError(e.localizedDescription)
        }

        return self.frc!
    }()

章节标题

要获取章节标题,请实现此方法。

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let sectionTitle = self.fetchedResultsController.sections?[section].name ?? "No Category Titles"
        return sectionTitle

}

Table 指数

要设置索引,您需要执行以下方法。

func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {

        return self.fetchedResultsController.sectionIndexTitles ?? [""]

}

Note the Quick Help Documentation when you click on sectionIndexTitles. The array of section index titles. The default implementation returns the array created by calling sectionIndexTitleForSectionName: on all the known sections. You should override this method if you want to return a different array for the section index. You only need this method if you use a section index.

来源

如果您想在上下文中看到这一点,要了解如何以这种方式使用 NSFetchedResultsController 的要点,您可以查看 my sample at this location.

候补 (Arrays/Dictionaries)

还有一些其他教程介绍如何从数组和字典构建索引(但我推荐上述方法作为最简单的方法)。

替代实施

注意:本节中的代码来自备用教程 #1

 // `UIKit` convenience class for sectioning a table
    let collation = UILocalizedIndexedCollation.currentCollation()
        as UILocalizedIndexedCollation
....
/* 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 {
            return self.collation.sectionTitles[section] as String
        }
        return ""
    }

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

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