Swift 3,按属性排序类并填充表视图

时间:2017-04-06 08:29:29

标签: uitableview sorting swift3

我是一个完整的初学者,并在互联网上寻找解决方案。 我想按距离对用户进行排序,并在表格视图中显示名称(按最近到最远距离排序)。 我能够在表视图中对另一个数组进行排序并显示,并且由于stackoverflow搜索,我能够按距离对其他位置进行排序。 但是我无法把它放在一起,并在表格视图中显示这些地方的名称。

我希望我描述的一切都足以让你理解我的问题。

import UIKit
import CoreLocation

class Places {

let name: String
let facility: String
let operated: String
let location: CLLocation

init(name: String, facility: String, operated: String, location: CLLocation){

    self.name = name
    self.facility = facility
    self.operated = operated
    self.location = location

}

}

let place1 = Places(name: "Name1", facility: "Hospital", operated: "privat", location: CLLocation(latitude: 12.953761, longitude: 100.906278))
let place2 = Places(name: "Name2", facility: "Hospital", operated: "privat", location: CLLocation(latitude: 12.944278, longitude: 100.887897))
let place3 = Places(name: "Name3", facility: "Hospital", operated: "privat", location: CLLocation(latitude: 12.935769, longitude: 100.886871))
let place4 = Places(name: "Name4", facility: "Hospital", operated: "sozial", location: CLLocation(latitude: 12.927889, longitude:  100.884304))
let place5 = Places(name: "Name5", facility: "Hospital", operated: "sozial", location: CLLocation(latitude: 12.966825, longitude: 100.906108))

var places: [Places] = [place1, place2, place3, place4, place5]
var locationManager = CLLocationManager()

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate{

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

    return(places.count)
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")

//Here comes the error        
cell.textLabel?.text = places.name[indexPath.row] 
    tableView.tableFooterView = UIView(frame: .zero)
    return(cell)
}

1 个答案:

答案 0 :(得分:0)

您需要先与subscript Array name,然后才需要访问其属性facilityoperatedlocationcell.textLabel?.text = places[indexPath.row].name 。< / p>

应该是

cell.textLabel?.text = places.name[indexPath.row] 

而不是

tableFooterView

注意:请勿在{{1​​}}方法中设置cellForRowAt,而不是在viewDidLoad内设置override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView(frame: .zero) }

.lg-dropdown-content .lg-menu ul