UiTableView生成的单元格数

时间:2017-10-23 14:24:09

标签: ios swift uitableview

我有两个viewControllers。第一个是步进器:

var steppers : UIStepper?

@IBOutlet weak var hourLabel: UILabel!
@IBOutlet weak var stepper: UIStepper!

@IBAction func stepper(_ sender: UIStepper) {
     hourLabel.text = String(sender.value)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let np = segue.destination as? CourseClass2 {
        np.numberPlaces = Int(stepper.value)
    }
}

和第二个用tableView:

private let resueIdentifier = "MyTableViewCell"

extension UIViewController {
    func present(viewController : UIViewController, completion : (() -> ())? = nil ){
        if let presented = self.presentedViewController {
            presented.dismiss(animated: true, completion: {
                self.present(viewController, animated: true, completion: completion)
            })
        } else {
            self.present(viewController, animated: true, completion: completion)
        }
    }
}

class CourseClass2: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var locationManager:CLLocationManager?
    let minimumSpacing : CGFloat = 15 //CGFloat(MAXFLOAT)
    let cellWidth: CGFloat = 250
    let radius = 5000 // 5km
    var category : QCategoryy?
    var currentLocation : CLLocationCoordinate2D?
    var places: [QPlace] = []
    var isLoading = false
    var response : QNearbyPlacesResponse?
    var rows = 0
    var numberPlaces = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = category?.name
        tableView.dataSource = self
        tableView.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        determineMyCurrentLocation()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        rows = 0
     /*   insertRowsMode3()
        tableView.reloadData()  */
        category?.markView()
    }

    @IBAction func refreshTapped(_ sender: Any) {
        rows = 0
    /*    insertRowsMode3()  */
        tableView.reloadData()
    }

    func canLoadMore() -> Bool {
        if isLoading {
            return false
        }

        if let response = self.response {
            if (!response.canLoadMore()) {
                return false
            }
        }

        return true
    }

    func loadPlaces(_ force:Bool) {
        if !force {
            if !canLoadMore() {
                return
            }
        }

        print("load more")
        isLoading = true
        NearbyPlaces.getNearbyPlaces(by: category?.name ?? "food", coordinates: currentLocation!, radius: radius, token: self.response?.nextPageToken, completion: didReceiveResponse)
    }

    func didReceiveResponse(response:QNearbyPlacesResponse?, error : Error?) -> Void {
        if let error = error {
            let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
            let actionDismiss = UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)
            let actionRetry = UIAlertAction(title: "Retry", style: .default, handler: { (action) in
                DispatchQueue.main.async {
                    self.loadPlaces(true)
                }
            })
            alertController.addAction(actionRetry)
            alertController.addAction(actionDismiss)
            DispatchQueue.main.async {
                self.present(viewController: alertController)

            }
        }
        if let response = response {
            self.response = response
            if response.status == "OK" {
                if let placesDownloaded = response.places {
                    places.append(contentsOf: placesDownloaded)
                }

               self.tableView?.reloadData()
            } else {
                let alert = UIAlertController.init(title: "Error", message: response.status, preferredStyle: .alert)
                alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
                alert.addAction(UIAlertAction.init(title: "Retry", style: .default, handler: { (action) in
                    DispatchQueue.main.async {
                        self.loadPlaces(true)
                    }
                }))
                 self.present(viewController: alert)
            }
            isLoading = false
        }
        else {
            print("response is nil")
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        print("numberOfsection Call")
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("numberOfRows Call")
        return  places.count   /*  rows   */
    }

    public  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: resueIdentifier, for: indexPath) as! MyTableViewCell

        let place = places[indexPath.row]
        cell.update(place: place)

        if indexPath.row == places.count - 1 {
            loadPlaces(false)
        }
        print("CellForRow Call")
        return (cell)
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        UIView.animate(withDuration: 0.2, animations: {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as! MyTableViewCell
    })

        performSegue(withIdentifier: "goToLast" , sender: indexPath.row)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete {
            places.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
    }

    func didReceiveUserLocation(_ userLocation:CLLocation) {
        currentLocation = userLocation.coordinate

        loadPlaces(true)
    }

我只添加了对问题有用的代码。如你所见,我试图从第一个VC传递到第二个这个值:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let np = segue.destination as? CourseClass2 {
        np.numberPlaces = Int(stepper.value)
    }
}

因为我想在第二个viewController中加载tableview时产生的单元格数量限制(我希望用户使用前一个控制器中的步进器选择此限制),我该怎么做必须修改tableView以确保生成的单元格数等于var numberPlaces的值?

1 个答案:

答案 0 :(得分:0)

我建议您限制pod install 委托方法单元格数内的单元格数

UITableView

通过这种方式,您将得到正确数量的单元格,但如果有太多地方,则只显示self.numberPlaces。

也许,您需要弄清楚一些排序,以便显示正确的位置。 (靠近,......)