Ios 我们是否可以将数据从表单元格传递到表视图,其中两个都是xib文件?

Ios 我们是否可以将数据从表单元格传递到表视图,其中两个都是xib文件?,ios,swift,xcode,uitableview,xib,Ios,Swift,Xcode,Uitableview,Xib,我想将表单元数据(xib文件)传递给表视图(也是一个xib文件)。我尝试使用下面的代码传递数据,但没有得到适当的结果 PropertyCell.swift import UIKit class PropertyCell: UITableViewCell { @IBOutlet weak var propertyCodeLbl: UILabel! @IBOutlet weak var addressLbl: UILabel! } import UIK

我想将表单元数据(xib文件)传递给表视图(也是一个xib文件)。我尝试使用下面的代码传递数据,但没有得到适当的结果

PropertyCell.swift

    import UIKit

    class PropertyCell: UITableViewCell {

    @IBOutlet weak var propertyCodeLbl: UILabel!
    @IBOutlet weak var addressLbl: UILabel!

    }
import UIKit
import Alamofire

class PropertyTableVC: UITableViewController {


    @IBOutlet var propertyTabel: UITableView!

    let URL_Landlord_Property_List = "http://127.0.0.1/source/api/LandlordPropertyList.php"
    var count: Int = 0
    var landlordPropertyArray: [PropertyList]? = []

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchData()
        propertyTabel.dataSource = self
        propertyTabel.delegate = self

        let nibName = UINib(nibName: "PropertyCell", bundle:nil)
        self.propertyTabel.register(nibName, forCellReuseIdentifier: "Cell")
    }

    func fetchData(){
        let urlRequest = URLRequest(url: URL(string: URL_Landlord_Property_List)!)
        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if error != nil{
                print(error!)
                return
            }
            print(data!)
            self.landlordPropertyArray = [PropertyList]()
            self.count = (self.landlordPropertyArray?.count)!
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

                if let datafromjson = json["landlords_property_list"] as? [[String: AnyObject]] {
                    print(datafromjson)
                    for data in datafromjson{
                        var property = PropertyList()
                        if let id = data["ID"] as? Int,let code = data["Code"] as? String, let address1 = data["Address"] as? String
                        {
                            property.id = id
                            property.code = code
                            property.address1 = address1

                        }
                        self.landlordPropertyArray?.append(property)
                    }
                    print(self.landlordPropertyArray)
                }
                DispatchQueue.main.async {
                    self.propertyTabel.reloadData()
                }
            }catch let error {
                print(error)
            }
        }
        task.resume()
    }

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (landlordPropertyArray?.count)!
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Configure the cell...
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PropertyCell
        cell.propertyCodeLbl.text = self.landlordPropertyArray?[indexPath.item].code
        cell.addressLbl.text = self.landlordPropertyArray?[indexPath.item].address1
        return cell
    } 
}
我已附上下面PropertyCell的屏幕截图-

PropertyCell.xib

PropertyTableVC.swift

    import UIKit

    class PropertyCell: UITableViewCell {

    @IBOutlet weak var propertyCodeLbl: UILabel!
    @IBOutlet weak var addressLbl: UILabel!

    }
import UIKit
import Alamofire

class PropertyTableVC: UITableViewController {


    @IBOutlet var propertyTabel: UITableView!

    let URL_Landlord_Property_List = "http://127.0.0.1/source/api/LandlordPropertyList.php"
    var count: Int = 0
    var landlordPropertyArray: [PropertyList]? = []

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchData()
        propertyTabel.dataSource = self
        propertyTabel.delegate = self

        let nibName = UINib(nibName: "PropertyCell", bundle:nil)
        self.propertyTabel.register(nibName, forCellReuseIdentifier: "Cell")
    }

    func fetchData(){
        let urlRequest = URLRequest(url: URL(string: URL_Landlord_Property_List)!)
        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if error != nil{
                print(error!)
                return
            }
            print(data!)
            self.landlordPropertyArray = [PropertyList]()
            self.count = (self.landlordPropertyArray?.count)!
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

                if let datafromjson = json["landlords_property_list"] as? [[String: AnyObject]] {
                    print(datafromjson)
                    for data in datafromjson{
                        var property = PropertyList()
                        if let id = data["ID"] as? Int,let code = data["Code"] as? String, let address1 = data["Address"] as? String
                        {
                            property.id = id
                            property.code = code
                            property.address1 = address1

                        }
                        self.landlordPropertyArray?.append(property)
                    }
                    print(self.landlordPropertyArray)
                }
                DispatchQueue.main.async {
                    self.propertyTabel.reloadData()
                }
            }catch let error {
                print(error)
            }
        }
        task.resume()
    }

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (landlordPropertyArray?.count)!
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Configure the cell...
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PropertyCell
        cell.propertyCodeLbl.text = self.landlordPropertyArray?[indexPath.item].code
        cell.addressLbl.text = self.landlordPropertyArray?[indexPath.item].address1
        return cell
    } 
}
附上以下财产表的屏幕截图-

PropertyTableVC.xib


在tableview委托和数据源分配之后调用
fetchData()
函数

        propertyTabel.dataSource = self
        propertyTabel.delegate = self
最新答案是 像这样创建Cell类

import UIKit

class YourTableViewCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var timeDateLabel: UILabel!


override func awakeFromNib() {
    super.awakeFromNib()
    self.backgroundColor = UIColor.tableViewBackgroundColor()
    self.selectionStyle = .none
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

class func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> YourTableViewCell {
    let kYourTableViewCell = "YourTableViewCellIdentifier"
    tableView.register(UINib(nibName:"RRLoadQuestionsTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: kYourTableViewCell)
    let cell = tableView.dequeueReusableCell(withIdentifier: kYourTableViewCell, for: indexPath) as! YourTableViewCell

    return cell

}
}

然后创建UIViewController类并将UITableView放置在其上,并链接到outlet

class YourViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {

@IBOutlet weak var tableView: UITableView!


var dataSource =  [LoadYourData]()

// MARK: - Init & Deinit

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
    super.init(nibName: "YourViewController", bundle: Bundle.main)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

override func viewDidLoad() {
    super.viewDidLoad()
    setupViewControllerUI()
}

override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(true)

}

// MARK: - UIViewController Helper Methods

func setupViewControllerUI() {

    tableView.estimatedRowHeight = 44.0
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.delegate = self
     tableView.dataSource = self
    loadData()

}

func loadData() {

// Write here your API and reload tableview once you get response
}


// MARK: - UITableView Data Source

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

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = YourTableViewCell.cellForTableView(tableView: tableView, atIndexPath: indexPath)

 // assign here cell.name etc from dataSource
    return cell

}
您的TableViewCell:

import UIKit

protocol yourProtocolName { //add protocol here
func getDataFromTableViewCellToViewController (sender : self) //* as you need to pass the table view cell, so pass it as self
}

    class PropertyCell: UITableViewCell {

        @IBOutlet weak var propertyCodeLbl: UILabel!
        @IBOutlet weak var addressLbl: UILabel!
        var delegate : yourProtocolName? //set a delegate

        override func awakeFromNib() {
            super.awakeFromNib()
            if delegate != nil {
                delegate.getDataFromTableViewCellToViewController(sender :self) *
        }
    }
}
和您的ViewController:

import UIKit
import Alamofire

class PropertyTableVC: UITableViewController,yourProtocolName { //conform to the protocol you created in tableViewCell


    @IBOutlet var propertyTabel: UITableView!

    let URL_Landlord_Property_List = "http://127.0.0.1/source/api/LandlordPropertyList.php"
    var count: Int = 0
    var landlordPropertyArray: [PropertyList]? = []

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchData()
        propertyTabel.dataSource = self
        propertyTabel.delegate = self

        let nibName = UINib(nibName: "PropertyCell", bundle:nil)
        self.propertyTabel.register(nibName, forCellReuseIdentifier: "Cell")
    }

    func fetchData(){
        let urlRequest = URLRequest(url: URL(string: URL_Landlord_Property_List)!)
        let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
            if error != nil{
                print(error!)
                return
            }
            print(data!)
            self.landlordPropertyArray = [PropertyList]()
            self.count = (self.landlordPropertyArray?.count)!
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

                if let datafromjson = json["landlords_property_list"] as? [[String: AnyObject]] {
                    print(datafromjson)
                    for data in datafromjson{
                        var property = PropertyList()
                        if let id = data["ID"] as? Int,let code = data["Code"] as? String, let address1 = data["Address"] as? String
                        {
                            property.id = id
                            property.code = code
                            property.address1 = address1

                        }
                        self.landlordPropertyArray?.append(property)
                    }
                    print(self.landlordPropertyArray)
                }
                DispatchQueue.main.async {
                    self.propertyTabel.reloadData()
                }
            }catch let error {
                print(error)
            }
        }
        task.resume()
    }

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (landlordPropertyArray?.count)!
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Configure the cell...
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PropertyCell
        cell.propertyCodeLbl.text = self.landlordPropertyArray?[indexPath.item].code
        cell.addressLbl.text = self.landlordPropertyArray?[indexPath.item].address1
        return cell
    } 

    func getDataFromTableViewCellToViewController(sender :UITableViewCell) {
        //make a callback here
    }
}

(*)标记的字段已更新代码

是否尝试创建协议?DispatchQueue.main.async{self.propertyTable.reloadData()}-->将此代码添加到if let datafromjson=。。。。。{}@AshishBahl不,我没有尝试过协议,因为我以前没有使用过。你能给我举个简单的例子来使用它吗?@BoominadhaPrakashM谢谢。我按照你说的做了更改,但没有更改。请查看我的回答@SaurabhThank@you以获得回复。我做了上述代码中提到的更改,但未填充表。是否从服务器获得响应?是的,我从服务器获得响应,但未在表视图中填充。是否在从服务器获得响应后调用tableView reloadData?。在收到服务器的响应后调试tableview数据源。我尝试了这个@Josh,但它显示了相同的输出问题我如何在这里调用协议?@Saurabh我在回答中显示了它。请仔细阅读我在评论中提到的代码!我找到了。因此,我将进行必要的更改并重新运行代码。如果行得通,我一定会让你知道的。谢谢@ashishbahl您提供的代码向我显示了这个错误->
var委托:cellProtocol?重写func awakeFromNib(){super.awakeFromNib(),如果委托!=nil{delegate.getDataFromTableViewCellToViewController(发送方:UITableViewCell)//在UITableViewCell上显示错误}**错误**:无法将“UITableViewCell.type”类型的值转换为预期的参数类型“UITableViewCell”
I在Saurabh修改了我的答案