Я новичок в swift & Xcode (обучение самому себе с помощью учебников и stackoverflow). Я написал код, который добавляет места в список в TableView, и теперь я пытаюсь сортировать этот список мест в разделах.Сортировка UITableView в разделы
В частности, у меня есть ViewController, где я ввожу имя, окрестности и друга (все строки), и это добавляет место в нижней части моего TableView.
Я хочу сгруппировать этот список мест по соседству и отобразить все места в том же районе вместе в разделе, используя строку окрестности в качестве заголовка раздела.
Я близко, но я не правильно индексирую свои разделы. indexPath.section Я считаю, что я пропускаю ..
До сих пор у меня есть этот код в моем TableViewController:
// MARK: Properties
var places = [Place]()
override func viewDidLoad() {
super.viewDidLoad()
// Use the edit button item provided by the table view controller.
navigationItem.leftBarButtonItem = editButtonItem()
// Load any saved places, otherwise load sample data.
if let savedPlaces = loadPlaces() {
places += savedPlaces
}
else {
// Load the sample data.
loadSamplePlaces()
}
// Sort by neighborhood
places.sortInPlace { (place1, place2) -> Bool in
return place1.neighborhood < place2.neighborhood
}
}
// MARK: Getting Count, Number and Name of Neighborhoods
func getCountForNeighborhood(neighborhood:String) -> Int {
return places.filter { (place) -> Bool in
return place.neighborhood == neighborhood
}.count
}
func getNumberOfNeighborhoods() -> Int {
var neighborhoodCount = 0
var neighborhoodPrev = "Not a real neighborhood"
for place in places {
if place.neighborhood != neighborhoodPrev {
neighborhoodCount += 1
}
neighborhoodPrev = place.neighborhood
}
return neighborhoodCount
}
func getNeighborhoodForSection(section:Int) -> String {
var previousNeighborhood:String = "Not a real neighborhood"
var currentIndex = -1
for place in places {
if(place.neighborhood != previousNeighborhood) {
currentIndex += 1
}
if(currentIndex == section){
return place.neighborhood
}
previousNeighborhood = place.neighborhood
}
return "Unknown"
}
func loadSamplePlaces() {
let place1 = Place(name: "Motorino", neighborhood: "East Village", friend: "Maggles")!
let place2 = Place(name: "Bar Primi", neighborhood: "Lower East Side", friend: "Em")!
let place3 = Place(name: "El Carino", neighborhood: "Williamsburg", friend: "Ruby")!
places += [place1, place2, place3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//alter this for To Try, Been To sections =2
return getNumberOfNeighborhoods()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let neighborhood = getNeighborhoodForSection(section)
return getCountForNeighborhood(neighborhood)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "PlaceTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PlaceTableViewCell
// Fetches the appropriate place for the data source layout.
let place = places[indexPath.row]
cell.placeLabel.text = place.name
cell.neighborhoodLabel.text = place.neighborhood
cell.friendLabel.text = place.friend
return cell
}
//Add section headers
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return getNeighborhoodForSection(section)
}
Я довольно уверен, что это проблема с моим методом cellForRowAtIndexPath. Я думаю, что не хватает какой-то код, чтобы правильно индекс данные в разделах ...
Текущие сборки отображает