简体   繁体   English

自定义UITableViewCells未出现在UI TableView上

[英]Custom UITableViewCells not appearing on UI TableView

I am developing an app, and I have a TableView within my ViewController that I want to display custom UITableViewCells. 我正在开发一个应用程序,并且ViewController内有一个TableView,我想显示自定义UITableViewCells。 Here is my view controller class as it pertains to the table view: 这是我的视图控制器类,因为它与表视图有关:

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
}
}

Yet when I run the app, the cells do not appear in the table view: 但是,当我运行该应用程序时,单元格不会出现在表格视图中: 在此处输入图片说明

I've researched multiple tutorials and made sure that everything is entered correctly and connected in the storyboard. 我研究了多个教程,并确保所有内容都正确输入并连接到情节提要中。 What's going on? 这是怎么回事? Thanks so much for your help. 非常感谢你的帮助。

You need to call taskTable.reloadData() after your for loop that gets the tasks. 您需要在获取任务的for循环之后调用taskTable.reloadData()。 If that function takes a while to run, you might want to call taskTable.reloadData() in the loop after you add each task so they can see the table populating. 如果该函数需要一段时间才能运行,则可能需要在添加每个任务后在循环中调用taskTable.reloadData(),以便他们可以看到表正在填充。

A table view loads data in when the viewController that is its datasource first loads. 表视图是在其数据源的viewController首次加载时加载数据的。 Every time it's data changes, reloadData() must be called for it to run through the function cellForRowAtIndexPath again for each cell. 每次数据更改时,都必须调用reloadData()才能再次为每个单元格运行一次cellForRowAtIndexPath函数。 There are ways to do this for individual cells, but that is not necessary for most situations. 有一些方法可以对单个单元格执行此操作,但是在大多数情况下这不是必需的。 (Mainly when you have ridiculous amounts of work per whole table view reload to where you notice device lag) (主要是当每个表视图的工作量都非常可笑时,重新加载到设备滞后的位置)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM