CellForRowAt indexPath没有被称为iOS Swift

时间:2017-06-30 01:49:37

标签: ios swift uitableview

我已在tableView中以编程方式创建了ViewController,但是当我加载ViewController时,函数cellForRowAtIndexPath未被调用。

我看了很多关于StackOverflow的建议,但没有一个帮助解决这个问题。有人可以指导我出错的地方。

这是我的代码:

import UIKit
import AlgoliaSearch

class ReportVC: UIViewController, UITableViewDelegate, UITableViewDataSource, DrugMoleculesTVCProtocol {

    // FOR SCREEN DIMENSIONS
    let screenSize: CGRect = UIScreen.main.bounds
    var screenWidth: CGFloat
    var screenHeight: CGFloat
    var saveButton : UIBarButtonItem?
    var cancelButton: UIBarButtonItem?

    // For Table view
    var tableView    : UITableView     = UITableView()
    let cellIdentifier = "Cell"
    var tableViewCell : UITableViewCell = UITableViewCell()
    var selectedObjectsArray: Array = [Any]()

    required init?(coder aDecoder: NSCoder) {
        screenHeight = screenSize.height
        screenWidth = screenSize.width
        super.init(coder: aDecoder)

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Setting buttons for the Nav Bar
        saveButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.save, target: self, action: #selector(save))
        cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self, action: #selector(cancel))
        self.navigationItem.rightBarButtonItem  = saveButton
        self.navigationItem.leftBarButtonItem  = cancelButton
        self.edgesForExtendedLayout = [] // This ensures that the views dont go below the navigation bar


        // ADDING LABELS AND TEXT VIEWS
        let myObservationsLabel : UILabel =  {
            let label = UILabel()
            label.text = "My Observations"
            return label
        }()

        let myObservationsTextView : UITextView = {
           let textView = UITextView()
           textView.backgroundColor = UIColor.lightGray
           textView.font?.withSize(22.0)
           return textView
        }()


        let myLabel : UILabel =  {
            let label = UILabel()
            label.text = "Standard"
            return label
        }()

        let addButton : UIButton =  {
            let button = UIButton()
            button.setTitle("Add", for: .normal)
            button.setTitleColor(UIColor.darkGray, for: .normal)
            button.addTarget(self, action: #selector(addItems), for: .touchUpInside)
            return button
        }()

        let myTextField : UITextField = {
            let textField = UITextField()
            textField.placeholder = "Name"
            return textField
        }()


        let nextStepsLabel : UILabel =  {
            let label = UILabel()
            label.text = "Next Steps"
            return label
        }()

        // Add textView for Next steps
        let nextStepsTextView : UITextView = {
            let textView = UITextView()
            textView.backgroundColor = UIColor.lightGray
            textView.font?.withSize(22.0)
            return textView
        }()

        self.view.addSubview(myObservationsLabel)
        self.view.addSubview(myObservationsTextView)
        self.view.addSubview(myLabel)
        self.view.addSubview(addButton)


        tableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)

        // Setting datasource and Delegate for TableView
        tableView.delegate      =   self
        tableView.dataSource    =   self
        self.view.addSubview(tableView)

        self.view.addSubview(myTextField)
        self.view.addSubview(nextStepsLabel)
        self.view.addSubview(nextStepsTextView)

        // Disabling Auto Constraints to set constraints manually
        myObservationsLabel.translatesAutoresizingMaskIntoConstraints    = false
        myObservationsTextView.translatesAutoresizingMaskIntoConstraints = false
        myLabel.translatesAutoresizingMaskIntoConstraints                = false
        addButton.translatesAutoresizingMaskIntoConstraints              = false
        tableView.translatesAutoresizingMaskIntoConstraints              = false
        myTextField.translatesAutoresizingMaskIntoConstraints            = false
        nextStepsLabel.translatesAutoresizingMaskIntoConstraints         = false
        nextStepsTextView.translatesAutoresizingMaskIntoConstraints      = false

        // Adding views to dictionary
        let viewsDict = [
            "myObservationsLabel"    : myObservationsLabel,
            "myObservationsTextView" : myObservationsTextView,
            "myLabel"                : myLabel,
            "addButton"              : addButton,
            "tableView"              : tableView,
            "myTextField"            : myTextField,
            "nextStepsLabel"         : nextStepsLabel,
            "nextStepsTextView"      : nextStepsTextView
        ]

        // Setting Constraints to the views in Dictionary
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[myObservationsLabel(25)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[myObservationsLabel]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for myObservationsTextView
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[myObservationsLabel]-10-[myObservationsTextView(100)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[myObservationsTextView]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for nextStepsLabel
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[myObservationsTextView]-10-[nextStepsLabel(25)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[nextStepsLabel]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for nextStepsTextView
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[nextStepsLabel]-10-[nextStepsTextView(100)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[nextStepsTextView]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for myLabel
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[nextStepsTextView]-10-[myLabel(25)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[myLabel]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for addButton
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[nextStepsTextView]-10-[addButton(25)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[addButton]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for myTextField
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[addButton]-10-[myTextField(25)]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[myTextField]-10-|", options: [], metrics: nil, views: viewsDict))

        // Setting constraints for  Table view
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[myTextField]-10-[tableView]", options: [], metrics: nil, views: viewsDict))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[tableView]-10-|", options: [], metrics: nil, views: viewsDict))

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func save(sender: UIBarButtonItem){
        print("Clicked save button")
    }

    func cancel(sender: UIBarButtonItem){
        print("Clicked cancel button")
    }

    func addItems(sender:UIButton!) {
        print("addItems Button Clicked")
        self.performSegue(withIdentifier: "showSearchTable", sender: self)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension ReportVC {

    func setSelectedDrugMolecules(_ valueSent: [Any]){
        print("setSelectedDrugMolecules func called")
        self.selectedObjectsArray = valueSent
        print("self.selectedObjectsArray in func: \(self.selectedObjectsArray)")
        tableView.reloadData()
    }

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSearchTable" {
            let vc = segue.destination as! DrugMoleculesTVC
            vc.selectedObjectsArray = self.selectedObjectsArray
            vc.delegate = self
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        print("table view loaded in numberOfSections")
        return 1
    }


    // Return the number of rows for each section in your static table

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("printing numberOfRowsInSection:\(selectedObjectsArray.count)")
        return 10
    }

    // Return the row for the corresponding section and row

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("table view loaded in cellForRowAt")
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = "test"
        return cell
    }

    // Customize the section headings for each section
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        switch(section) {
        case 0: return "Drug Name"
        default: fatalError("Unknown section")
        }
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let row     = indexPath.row
        let section = indexPath.section

        if section == 0 && row == 0 {
            //The user has clicked on qualification cell
            print("TableView Section 0 Row 1 cell has been clicked")
        }
        else if section == 0 && row == 1 {
            // The user has clicked on languages spoken cell
            print("TableView Section 0 Row 2 cell has been clicked")
        }
    }

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

}

4 个答案:

答案 0 :(得分:1)

调用ç时,dataSource selectedObjectsArray为空。当section中的行数为0时,tableView不会调用cellForRowAt

因此,在调用selectedObjectsArray之前,您应该将某些内容放入numberOfRowsInSection

或者,当您设置selectedObjectsArray后,请致电tableView.reloadView

快速的方法是,您可以return 10(fixed number) numberOfRowsInSection查看用户界面是否有效。

答案 1 :(得分:1)

真正的罪魁祸首是我在为TableView #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; use std::fmt; use serde_json::Error; use serde::de::{self, Deserializer, Unexpected, Visitor}; #[derive(Serialize, Deserialize)] struct Example { #[serde(deserialize_with = "string_as_f64")] first: f64, second: f64, } fn string_as_f64<'de, D>(deserializer: D) -> Result<f64, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_f64(F64Visitor) } struct F64Visitor; impl<'de> Visitor<'de> for F64Visitor { type Value = f64; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a string representation of a f64") } fn visit_str<E>(self, value: &str) -> Result<f64, E> where E: de::Error, { value.parse::<f64>().map_err(|_err| { E::invalid_value(Unexpected::Str(value), &"a string representation of a f64") }) } } fn typed_example() -> Result<(), Error> { let data = r#"["3.141",1.618]"#; let e: Example = serde_json::from_str(data)?; println!("{} {}", e.first * 2.0, e.second * 2.0); Ok(()) } fn main() { typed_example().unwrap(); } 设置垂直约束时错过了 |

V:[myTextField]-10-[tableView]|

如果没有您的所有意见,我将无法弄明白,非常感谢!!

答案 2 :(得分:0)

我可以从您的获取代码中获得,datasourcedelegate UITableView正确。 ReloadData也在那里。 CGRect.Zero可能是真正的罪魁祸首。由于未定义框架,因此不会绘制TableView,因此不会调用其数据源方法。

作为开发人员,您应该尝试分离您的设计和逻辑部分。喜欢在Storyboard / Xib中创建所有视图和约束,无论你是免费的。它清理代码并使其易于理解。 希望能帮助到你。快乐编码!!

答案 3 :(得分:0)

您是否尝试更改tableView的框架添加了您正在使用

 tableView = `UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)`

尝试给它一些帧值而不是CGRect.zero(0,0,0,0)并尝试使用

 CGRect(x: 0, y:0, width: self.view.frame.size.width, height: self.view.frame.size.height)