Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 将列表分为多个部分以用于tableview索引_Ios_Arrays_Sorting_Dictionary_Swift - Fatal编程技术网

Ios 将列表分为多个部分以用于tableview索引

Ios 将列表分为多个部分以用于tableview索引,ios,arrays,sorting,dictionary,swift,Ios,Arrays,Sorting,Dictionary,Swift,我正在寻找一种最好的方法来获取一个列表,并将其排序为多个部分,以用于旁边的tableView索引。在我的示例中,按Make的第一个字母对Car对象进行排序。我在想我想要一本最多有26把钥匙的汽车物体词典,但现在还没用。如果有更好的方式让我忽略的话,我很乐意听到 任何帮助都将不胜感激 粘贴在操场样品 // Playground - noun: a place where people can play import UIKit var str = "Hello, playground" le

我正在寻找一种最好的方法来获取一个列表,并将其排序为多个部分,以用于旁边的tableView索引。在我的示例中,按Make的第一个字母对Car对象进行排序。我在想我想要一本最多有26把钥匙的汽车物体词典,但现在还没用。如果有更好的方式让我忽略的话,我很乐意听到

任何帮助都将不胜感激

粘贴在操场样品

// Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

let indexList = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

func gimmeOne(things: [String]) -> String {
    let randomNumber = Int(arc4random()) % things.count
    let choice = things[randomNumber]
    return choice
}

func gimmeCarMake() -> String {
    let makes = ["Ford","Audi","Hennessey","Acura","Infiniti","BMW","Lexus","Jeep","Subaru","Nissan","Aston Martin","Mercedes-Benz","Porsche","Toyota","Volkswagen","Scion","Mitsubishi","Mini","Lotus","Lamborghini","Jaguar","Hyundai","Citroën","Cadillac","Bugatti","Bentley","Alfa Romeo","Dodge"]
    return gimmeOne(makes)
}

class Car:NSObject {
    var make: String

    override init() {
        self.make = gimmeCarMake()
    }
}

//create list of cars
var carList = [Car]()
for _ in 0..<10 {
    carList.append(Car())
}
carList


//sort list
carList.sort { $0.make < $1.make }
carList


func firstLetter(text: String) -> String {
    let position = 0
    let index = advance(text.startIndex, position)
    let character = "\(text[index])"
    return character
}


//goal - to be used in tableView index section
//["A"] = ["Acura","Aston Martin","Audi"]
//["B"] = ["BMW","Bentley"]
//["C"] = ["Cadillac","Citroën"]
//["D"] = ["Dodge"]
编辑: 让我们看看我是否能失去剩下的名誉点数

我用代码给出了最终的答案,而且它非常通用,任何人只要稍作修改就可以使用它。如果您需要遵循步骤,请查看

希望它能帮助别人

//
//  ViewController.swift
//  tmpSortTable
//
// Solution from:
// http://www.pumpmybicep.com/2014/07/04/uitableview-sectioning-and-indexing/
//

import UIKit

class MyObject:NSObject {
    var thingA: String
    var thingB: String
    var section: Int?  //make room in your object for this

    class func gimmeOne(things: [String]) -> String {
        let randomNumber = Int(arc4random()) % things.count
        let choice = things[randomNumber]
        return choice
    }

    class func gimmeCarMake() -> String {
        let makes = ["Ford","Audi","Hennessey","Acura","Infiniti","BMW","Lexus","Jeep","Subaru","Nissan","Aston Martin","Mercedes-Benz","Porsche","Toyota","Volkswagen","Scion","Mitsubishi","Mini","Lotus","Lamborghini","Jaguar","Hyundai","Citroën","Cadillac","Bugatti","Bentley","Alfa Romeo","Dodge","Tesla"]
        return gimmeOne(makes)
    }

    class func gimmeCarModel() -> String {
        let model = ["F150","Mustang","LFA","S55","Raptor","Odyssey","NSX","4C","F40","F50","F70","LaFerrari","Camry","Silverado","Viper","Routan","Quattro","M100","P85 D","Stealth","Pinto","Accord"]
        return gimmeOne(model)
    }

    override init() {
        self.thingA = MyObject.gimmeCarMake()
        self.thingB = MyObject.gimmeCarModel()
    }

    override var description: String {
        return "\n\(thingA) \(thingB) in section \(section)"
    }
}



class ViewController: UITableViewController {

    //setup
    var data = [MyObject]()  //main list of data to be used

    override func viewDidLoad() {
        super.viewDidLoad()
        createData()
    }

    //create data or fill data any way you want
    func createData() {
        for _ in 0..<50 {
            data.append(MyObject())
        }
    }

    //now the important section stuff
    class Section {
        var items: [MyObject] = []

        func addItem(item: MyObject) {
            self.items.append(item)
        }

    }

    // `UIKit` convenience class for sectioning a table
    let collation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation
    var sections: [Section] {
        if self._sections != nil {
            return self._sections!
        }

        //identify item to section
        var items: [MyObject] = data.map { dataItem in
            dataItem.section = self.collation.sectionForObject(dataItem, collationStringSelector: "thingA")
            return dataItem
        }

        //create empty sections
        var sections = [Section]()
        for _ in 0..<self.collation.sectionIndexTitles.count {
            sections.append(Section())
        }

        //put each item into a section
        for item in items {
            sections[item.section!].addItem(item)
        }

        //sort each section
        for section in sections {
            section.items = self.collation.sortedArrayFromArray(section.items, collationStringSelector: "thingA") as [MyObject]
        }

        self._sections = sections
        return self._sections!
    }
    var _sections: [Section]?





    //TableView data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sections.count
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let item = self.sections[indexPath.section].items[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel.text = "\(item.thingA) \(item.thingB)"
        return cell
    }

    /* 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].items.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)
    }

}

您可以使用下面的代码并执行buildIndexwords来获得如下内容:

[A、[Acura、Auston Martin、奥迪], B、 [宝马,宾利], C、 [卡迪拉克,雪铁龙], .... ]


您可以使用下面的代码并执行buildIndexwords来获得如下内容:

[A、[Acura、Auston Martin、奥迪], B、 [宝马,宾利], C、 [卡迪拉克,雪铁龙], .... ]

在Swift中查看本教程。您将希望使用UILocalizedIndexedCollation便利类来创建索引,而不是手动或编程。它使用项目本地化列表中定义的区域设置。这样,您就不必自己创建列表,也不必编写代码来创建列表,并且在添加/删除更多条目时,需要的维护更少。这也将能够利用您在应用程序中最终进行的任何本地化

您还可以查看有关使用该类的更多详细信息。

在Swift中查看本教程。您将希望使用UILocalizedIndexedCollation便利类来创建索引,而不是手动或编程。它使用项目本地化列表中定义的区域设置。这样,您就不必自己创建列表,也不必编写代码来创建列表,并且在添加/删除更多条目时,需要的维护更少。这也将能够利用您在应用程序中最终进行的任何本地化


您还可以查看有关使用该类的更多详细信息。

Brocken URL。请检查。@SazzadHissainKhan我链接到的教程现在不见了。我添加了一个替换。Brocken URL。请检查。@SazzadHissainKhan我链接到的教程现在不见了。我加了一个替代品。
import Foundation

let makes = ["Ford","Audi","Hennessey","Acura","Infiniti","BMW","Lexus","Jeep","Subaru","Nissan","Aston Martin","Mercedes-Benz","Porsche","Toyota","Volkswagen","Scion","Mitsubishi","Mini","Lotus","Lamborghini","Jaguar","Hyundai","Citroën","Cadillac","Bugatti","Bentley","Alfa Romeo","Dodge"]

let words = makes.sorted({$0 < $1})

typealias Entry = (Character, [String])

func distinct<T: Equatable>(source: [T]) -> [T] {
  var unique = [T]()
  for item in source {
    if !contains(unique, item) {
      unique.append(item)
    }
  }
  return unique
}

func buildIndex(words: [String]) -> [Entry] {
  let letters = words.map {
    (word) -> Character in
    Character(word.substringToIndex(advance(word.startIndex, 1)
      ).uppercaseString)
  }
  let distinctLetters = distinct(letters)

  return distinctLetters.map {
    (letter) -> Entry in
    return (letter, words.filter {
      (word) -> Bool in
     Character(word.substringToIndex(advance(word.startIndex, 1)
       ).uppercaseString) == letter
    })
  }
}