Ios 在swift中添加范围栏
该应用程序在一个带有搜索栏的表格视图中显示它正在使用的汽车零件列表(汽车零件、类型、年份、国家) 现在我决定添加一个范围栏来过滤结果,我肯定我把代码搞糟了。要添加范围栏的行中有许多错误。这是注释Ios 在swift中添加范围栏,ios,swift,uisearchbar,Ios,Swift,Uisearchbar,该应用程序在一个带有搜索栏的表格视图中显示它正在使用的汽车零件列表(汽车零件、类型、年份、国家) 现在我决定添加一个范围栏来过滤结果,我肯定我把代码搞糟了。要添加范围栏的行中有许多错误。这是注释//ScopeBar try之后的最后20行,除了这最后几行之外,我在viewDidLoad()中添加了一个代码来显示我想要的标题 我做错了什么?任何帮助都是非常受欢迎的,我正在努力修复这两天已经没有运气了 import UIKit import CoreData class DictionaryTab
//ScopeBar try
之后的最后20行,除了这最后几行之外,我在viewDidLoad()
中添加了一个代码来显示我想要的标题
我做错了什么?任何帮助都是非常受欢迎的,我正在努力修复这两天已经没有运气了
import UIKit
import CoreData
class DictionaryTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchResultsUpdating
{
var searchController:UISearchController!
var searchResults:[Dictionary] = []
private var dictionaryItems:[Dictionary] = []
private var cockpitDict = [String: [Dictionary]]()
var sectionTitles = [String]()
var fetchResultController:NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
// ScopeBar Try
searchController.searchBar.scopeButtonTitles = ["All", "type", "year", "country"]
tableView.tableHeaderView = searchController.searchBar
// Load menu items from database
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
searchController.searchBar.placeholder = "Search ..."
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style:
.Plain, target: nil, action: nil)
// Enable self sizing cells
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
createCockpitDict()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createCockpitDict(){
for item in dictionaryItems {
guard let word = item.word else {
break
}
// Get the first letter of the word and build the dictionary
let wordKey = word.substringToIndex(word.startIndex.advancedBy(1))
if var cockpitItems = cockpitDict[wordKey] {
cockpitItems.append(item)
cockpitDict[wordKey] = cockpitItems
} else {
cockpitDict[wordKey] = [item]
}
}
// Get the section titles from the dictionary's keys and sort them in ascending order
sectionTitles = [String](cockpitDict.keys)
sectionTitles = sectionTitles.sort({ $0 < $1 })
}
// create a standard way to get a Dictionary from a index path
func itemForIndexPath (indexPath: NSIndexPath) -> Dictionary? {
var result: Dictionary? = nil
if searchController.active {
result = searchResults[indexPath.row]
}else{
let wordKey = sectionTitles[indexPath.section]
if let items = cockpitDict[wordKey]{
result = items[indexPath.row]
}
}
return result
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//assume a single section after a search
return (searchController.active) ? 1 : sectionTitles.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active {
return searchResults.count
} else {
// Return the number of rows in the section.
let wordKey = sectionTitles[section]
if let items = cockpitDict[wordKey] {
return items.count
}
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DictionaryTableViewCell
//let dictionary = (searchController.active) ? searchResults[indexPath.row]: dictionaryItems[indexPath.row]
if let dictionary = itemForIndexPath(indexPath){
cell.wordLabel.text = dictionary.word
cell.definitionSmallLabel.text = dictionary.definition
cell.typeLabel.text = dictionary.type
cell.yearLabel.text = dictionary.year
cell.countryLabel.text = dictionary.country
}else{
print("Cell error with path\(indexPath)")
}
return cell
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return sectionTitles
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
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
if let dictionary = itemForIndexPath(indexPath){
destinationController.dictionary = dictionary
}else{
print("Segue error with path \(indexPath)")
}
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
})
}
}
//ScopeBar try: all lines below got many errors I can not figure out how to fix it :(
func filterContentForSearchText(searchText: String, scope: String = "All") {
dictionaryItems = cockpitDict.filter({( cockpitDict : Dictionary) -> Bool in
let categoryMatch = (scope == "All") || (cockpitDict.category == scope)
return categoryMatch && cockpitDict.name.lowercaseString.containsString(searchText.lowercaseString)
})
tableView.reloadData()
}
extension DictionaryTableViewController:UISearchBarDelegate {
// MARK: - UISearchBar Delegate
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
}
extension DictionaryTableViewController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
filterContentForSearchText(searchController.searchBar.text!, scope: scope)
}
}
导入UIKit
导入CoreData
类字典TableViewController:UITableViewController、NSFetchedResultsControllerDelegate、UISearchResultsUpdated
{
var searchController:UISearchController!
var searchResults:[字典]=[]
私有变量字典项:[字典]=[]
私有变量cockpitDict=[字符串:[字典]]()
var sectionTitles=[String]()
var fetchResultController:NSFetchedResultsController!
重写func viewDidLoad(){
super.viewDidLoad()
//范围杆试验
searchController.searchBar.ScopeButtonTiles=[“所有”、“类型”、“年份”、“国家”]
tableView.tableHeaderView=searchController.searchBar
//从数据库加载菜单项
如果让managedObjectContext=(UIApplication.sharedApplication().delegate为?AppDelegate)?.managedObjectContext{
let fetchRequest=NSFetchRequest(entityName:“DictionaryEntity”)
做{
dictionaryItems=尝试managedObjectContext.executeFetchRequest(fetchRequest)作为![Dictionary]
}抓住{
打印(“检索记录失败”)
打印(错误)
}
}
searchController=UISearchController(searchResultsController:nil)
tableView.tableHeaderView=searchController.searchBar
searchController.SearchResultsUpdate=self
searchController.dimsBackgroundDuringPresentation=false
searchController.searchBar.placeholder=“搜索…”
navigationItem.backBarButtonItem=UIBarButtonItem(标题:),样式:
.普通,目标:无,行动:无)
//启用自调整单元格大小
tableView.estimatedRowHeight=100.0
tableView.rowHeight=UITableViewAutomaticDimension
createCockpitDict()
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
func createCockpitDict(){
对于字典项中的项{
guard let word=item.word else{
打破
}
//获取单词的第一个字母并建立字典
让wordKey=word.substringToIndex(word.startIndex.advancedBy(1))
如果var cockpitems=cockpidict[wordKey]{
cockpitItems.append(项目)
cockpitDict[wordKey]=cockpitItems
}否则{
cockpitDict[wordKey]=[item]
}
}
//从字典的键中获取章节标题并按升序排序
sectionTitles=[String](cockpitDict.keys)
sectionTitles=sectionTitles.sort({$0<$1})
}
//创建从索引路径获取词典的标准方法
func itemforindepath(indepath:nsindepath)->字典{
变量结果:字典?=nil
如果searchController.active{
结果=搜索结果[indexPath.row]
}否则{
让wordKey=sectionTitles[indexPath.section]
如果let items=cockpidict[wordKey]{
结果=项[indexPath.row]
}
}
返回结果
}
//标记:-表视图数据源
重写函数tableView(tableView:UITableView,titleForHeaderInSection:Int)->String{
返回章节标题[章节]
}
重写func numberOfSectionsInTableView(tableView:UITableView)->Int{
//在搜索后假设一个部分
返回(searchController.active)?1:sectionTitles.count
}
重写func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
如果searchController.active{
返回searchResults.count
}否则{
//返回节中的行数。
让wordKey=sectionTitles[section]
如果let items=cockpidict[wordKey]{
返回项目。计数
}
返回0
}
}
重写func tableView(tableView:UITableView,cellForRowAtIndexPath:nsindepath)->UITableView单元格{
让cell=tableView.dequeueReusableCellWithIdentifier(“cell”,forIndexPath:indexPath)作为!DictionaryTableViewCell
//let dictionary=(searchController.active)?searchResults[indexPath.row]:dictionaryItems[indexPath.row]
如果let dictionary=itemForIndexPath(indexPath){
cell.wordLabel.text=dictionary.word
cell.definitionSmallLabel.text=dictionary.definition
cell.typeLabel.text=dictionary.type
cell.yearLabel.text=dictionary.year
cell.countryLabel.text=dictionary.country
}否则{
打印(“路径为\(indexPath)的单元格错误”)
}
返回单元
}
覆盖func SECTIONINDEXTITLESSFORTABLEVIEW(表视图:UITableView)->[字符串]{
返回章节标题
}
//替代以支持表视图的条件编辑。
重写func tableView(tableView:UITableView,canEditRowAtIndexPath:nsindepath)->Bool{
//如果不希望指定的项可编辑,则返回false。
如果searchController.active{
返回错误
}否则{
返回真值
}
}
覆盖函数prepareforsgue(segue:UIStoryboardSegue,sender:AnyObject?){
如果segue.identifier==“showDi
dictionaryItems = cockpitDict.filter({( cockpitDict : Dictionary) -> Bool in
let categoryMatch = (scope == "All") || (cockpitDict.category == scope)
return categoryMatch && cockpitDict.name.lowercaseString.containsString(searchText.lowercaseString)
})
private var cockpitDict = [String: [Dictionary]]()
dictionaryItems = cockpitDict.filter({(key, value) -> Bool in
let categoryMatch = (scope == "All") || (value.category == scope)
return categoryMatch && value.name.lowercaseString.containsString(searchText.lowercaseString)
})
override func viewDidLoad() {
super.viewDidLoad()
// Load menu items from database
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
searchController.searchBar.placeholder = "Search ..."
// you were setting before initialization
searchController.searchBar.scopeButtonTitles = ["All", "type", "year", "country"]
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style:
.Plain, target: nil, action: nil)
// Enable self sizing cells
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
createCockpitDict()
}
func filterContentForSearchText(var searchText: String, scope: NSInteger) {
searchText = searchText.lowercaseString;
func checkString(strData: String, strSearchData: String)-> Bool{
return strData.rangeOfString(strSearchData, options:
NSStringCompareOptions.CaseInsensitiveSearch) != nil
}
searchResults = dictionaryItems.filter({ (dictionary:Dictionary) -> Bool in
switch scope {
case 0:
return (checkString(dictionary.word!, strSearchData: searchText) || checkString(dictionary.type!, strSearchData: searchText) || checkString(dictionary.country!, strSearchData: searchText) || checkString(dictionary.year!, strSearchData: searchText))
case 1:
return checkString(dictionary.type!, strSearchData: searchText)
case 2:
return checkString(dictionary.year!, strSearchData: searchText)
case 3:
return checkString(dictionary.country!, strSearchData: searchText)
default:
return true;
}
})
tableView.reloadData()
}
// MARK: - UISearchBar Delegate
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
filterContentForSearchText(searchBar.text!, scope: searchBar.selectedScopeButtonIndex)
}
// MARK: - UISearchResultsUpdating Delegate - comment older method so duplicate method error will be vanished
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
filterContentForSearchText(searchController.searchBar.text!, scope: searchBar.selectedScopeButtonIndex)
}