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

问题描述 投票:5回答:2

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

PropertyCell.swift

    import UIKit

    class PropertyCell: UITableViewCell {

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

    }

我在下面附上了PropertyCell的截图 -

PropertyCell.xib

PropertyCell.xib file

PropertyTableVC.swift

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

PropertyTableVC.xib file

ios swift xcode uitableview xib
2个回答
0
投票

你的UITableViewCell:

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

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


0
投票

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

        propertyTabel.dataSource = self
        propertyTabel.delegate = self

更新的答案是像这样创建单元格类

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

}
© www.soinside.com 2019 - 2024. All rights reserved.