自定义UITableViewCells没有出现在UI TableView上

时间:2016-06-24 21:58:39

标签: ios iphone swift uitableview

我正在开发一个应用程序,我在ViewController中有一个TableView,我想显示自定义UITableViewCells。这是我的视图控制器类,因为它与表视图有关:

import UIKit
import MapKit
import CoreLocation
import Firebase
import FirebaseAuth
import FirebaseDatabase


class FirstViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var taskTable: UITableView!
var tasks = [Task]()
var locationCurrent: CLLocation?
private var _ref = FIRDatabase.database().reference()


var ref: FIRDatabaseReference {
    return _ref
}


@IBOutlet weak var welcomeLabel: UILabel!


var _user = FIRAuth.auth()?.currentUser

let cellIdentifier = "TaskTableViewCell"

@IBOutlet weak var homeMap: MKMapView!
let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    self.locationManager.delegate = self
    self.homeMap.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
    getMapAnnotations()
    self.taskTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    loadTasks()
    taskTable.delegate = self
    taskTable.dataSource = self

    var refHandle = self.ref.child("user_profile").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
        let usersDict = snapshot.value as? NSDictionary
        let userDetails = usersDict?.objectForKey((self._user?.uid)!)

        if (userDetails?.objectForKey("name") != nil) {
        self.welcomeLabel.text = "Welcome, \(userDetails?.objectForKey("name") as! String)"
        }
    })

    // Do any additional setup after loading the view, typically from a nib.

}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations.last

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))

    self.homeMap.setRegion(region, animated: true)

    self.locationManager.stopUpdatingLocation()

    self.homeMap.showsUserLocation = true

    locationCurrent = (manager.location)!

}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("Errors: " + error.localizedDescription)
}

func loadTasks() {

    var title: String?
    var id: String?
    var distance: Double?

    var locationDict: [String:CLLocation] = [:]
    var refHandle = self.ref.child("tasks").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
        let tasksDict = snapshot.value as? NSDictionary
        for i in 0 ..< tasksDict!.count {
            let taskId = tasksDict!.allKeys[i] as! String
            print (taskId)
            id = taskId
            let task = tasksDict!.objectForKey(taskId) as! NSDictionary
            print (task)
            let lat = task.objectForKey("latitude") as! String
            let long = task.objectForKey("longitude") as! String
            title = task.objectForKey("title") as? String
            let latNum = Double(lat)! as CLLocationDegrees
            let longNum = Double(long)! as CLLocationDegrees
            print (latNum)
            print (longNum)
            let pointCoordinates: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latNum, longNum)
            let pointLocation = CLLocation()
            pointLocation.dynamicType.init(latitude: latNum, longitude: longNum)
            locationDict[taskId] = pointLocation
            print("yes")

            if (self.locationCurrent!.distanceFromLocation(pointLocation) < 1000000000) {
                distance = self.locationCurrent!.distanceFromLocation(pointLocation)
                var task = Task(title: title, id: id, distance: distance)
                self.tasks += [task]
                print("yes yes")
                print (task._title)
            }
        }

    })

}

func numberOfSections(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tasks.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TaskTableViewCell
    cell.titleLabel.text! = tasks[indexPath.row]._title!
    cell.distanceLabel.text! = "\(tasks[indexPath.row]._distance) m away"

    return cell
}
}

然而,当我运行应用程序时,单元格不会出现在表格视图中: enter image description here

我研究了多个教程,并确保所有内容都正确输入并连接到故事板中。这是怎么回事?非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您需要在获取任务的for循环之后调用taskTable.reloadData()。如果该函数需要一段时间才能运行,您可能希望在添加每个任务后在循环中调用taskTable.reloadData(),以便他们可以看到填充的表。

表视图在首次加载作为其数据源的viewController时加载数据。每次数据发生更改时,都必须调用reloadData(),以便为每个单元格再次运行函数cellForRowAtIndexPath。对于单个细胞,有很多方法可以做到这一点,但对于大多数情况来说,这不是必需的。 (主要是当你在整个表视图中有大量的工作重新加载到你注意到设备滞后的地方时)