Uitableview 向搜索栏添加索引

Uitableview 向搜索栏添加索引,uitableview,core-data,swift2,uisearchbar,xcode7,Uitableview,Core Data,Swift2,Uisearchbar,Xcode7,需要帮助来更正此代码我有一个coredata应用程序,上面有餐厅名称和地址,还有一个搜索栏,它正在工作。我想添加的是一个索引和一个索引,如下图所示(箭头)字符串?{return“dictionaryItems(section)”}您有一个输入错误:方法是titleForHeaderInSection(请注意)。@pbasdf感谢这是我的错误,但错误仍然是一样的,我正在尝试的是在右侧有一个节和一个带有字母表的索引,就像iphone上的联系人一样。我认为代码有问题…:(嗨,我修正了我的输入错误,但仍

需要帮助来更正此代码
我有一个coredata应用程序,上面有餐厅名称和地址,还有一个搜索栏,它正在工作。我想添加的是一个索引和一个索引,如下图所示(箭头)<欢迎任何帮助。提前谢谢

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
            })
        }
}


我试图在我的表视图中包含索引(左边的箭头)和索引标题(右边的箭头)


标题或标题部分的覆盖函数中存在打字错误

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

我建议使用Xcode的自动完成功能。这样,你就不会陷入像这样阴险的错误中

更新: 您还需要提供这两种方法来查看节标题和节索引标题

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上使用内置属性。其中最重要的部分是设置sectionNameKeyPath(应该是保存标题的托管对象属性)

段落名 要获取章节标题,请实现此方法

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

}
表索引 要设置索引,请实现以下方法

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

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

}
单击时请注意快速帮助文档 节索引。节索引标题的数组。默认值 实现返回通过调用 sectionIndexTitleForSectionName:在所有已知节上。你应该 如果要为对象返回其他数组,请重写此方法 节索引。只有在使用节索引时才需要此方法

来源 如果您想在上下文中看到这一点,那么要获得如何以这种方式使用NSFetchedResultsController的要点,您可以签出

备选(数组/字典) 还有一些关于如何从数组和字典构建索引的其他教程(但我推荐上面的方法作为最简单的方法)

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


您得到的错误是什么?错误:方法不会覆盖其超类中的任何方法。。。。。。。。。。。。。。。。。。。。。。。。。。。重写func tableview(tableview:UITableView,标题ForHeaderSection:Int)->字符串?{return“dictionaryItems(section)”}您有一个输入错误:方法是
titleForHeaderInSection
(请注意)。@pbasdf感谢这是我的错误,但错误仍然是一样的,我正在尝试的是在右侧有一个节和一个带有字母表的索引,就像iphone上的联系人一样。我认为代码有问题…:(
嗨,我修正了我的输入错误,但仍然没有显示索引和IndexTitle。还有其他提示吗?:)@Jade,你还需要提供sectionIndexTitlesForTableView来查看索引。我还用示例代码更新了我的答案,演示了它的工作原理。我对此进行了测试,并在运行iOS 9.0的iPhone6上运行。如果不行,请告诉我几件事:1。确保节的数量与节索引标题的数量相匹配(在右侧),它按顺序工作,因此如果您提供的节数较少,它将导航到错误的节。2.您可以在每个部分中获得整个数据库,因为您自己提供它;在函数numberOfRowsInSection中,UITableViewDataSource要求提供该特定节的项数,您的工作是在cellForRowAtIndexPath中为其指定正确的数字和正确的表视图单元格。因此,如果要按字母顺序执行,请根据numberOfRowsInSection中的节数筛选出数组。例如,在A部分中,返回数据库中以字母“A”开头的项数,而不是返回整个数组的长度。因此,我的代码不能用于索引,我必须更改为您的。我想从appcoda教程中为这段代码添加一些东西:(@Manolo-试试NSFRC,我想你会发现它是一个更干净的解决方案。请参阅我的源代码(上面的链接)了解如何在使用NSFRC时处理典型的tableview委托/数据源方法。我认为本教程使用的是较旧的方法,NSFRC更快、更易于使用、更高效。感谢您的时间,但我的知识不足以进行所有这些更改,我想知道是否有人可以帮助我使用本教程中的代码并告诉我为什么我不能让它工作。@Manolo你有一个单独的问题贴在你的代码的某个地方吗?如果你可以分享,那么我可以帮助你的具体问题。@Tommie C.我没有其他问题,但这是我试图更改和学习的教程中的代码。。。
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let sectionTitle = self.fetchedResultsController.sections?[section].name ?? "No Category Titles"
        return sectionTitle

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

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

}
 // `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)
    }