草庐IT

ios - 将数据从数组加载到 UITableView 单元格

coder 2024-01-28 原文

我对快速编程和尝试构建一个应用程序来接受订单并将它们转发给管理应用程序还很陌生。我的数据没有加载到我的 UITableView 中,我不确定为什么,据我所知,我已经按照书中的规定完成了所有操作。我正在从我创建的节点服务器加载数据,当打印数组的内容时,所有项目都打印为键值对值。 UIimages 正在加载到每个 tableView 单元格中,但标签没有加载,并且在设置标签并打印它们之后,标签的值仍然为 nil。

我创建了一个名为 PizzaListTableViewController 的 TableView 类和一个名为 PizzaTableViewCell 的自定义 TableViewCell 。我在 Storyboard界面构建器中添加了一个 UIimage 和三个标签。

Structure is: ViewController > TableView > TableViewCell > Image, Labels

我的主 VC 连接到它的 ViewController.class 我的 TableViewCell 连接到它的 TableViewCell.class 我有一个标识符并将其链接起来,按照下面的代码 我链接了所有的网点。任何帮助将不胜感激!

我曾尝试重写类,断开所有 socket 连接并重新连接它们,在设置标签的方法中赋值,但没有成功。

class PizzaListTableViewController: UITableViewController {
    var pizzas: [Pizza] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        //title you will see on the app screen at the top of the table view
        navigationItem.title = "Drink Selection"

        //tableView.estimatedRowHeight = 134
        //tableView.rowHeight = UITableViewAutomaticDimension

        fetchInventory { pizzas in
            guard pizzas != nil else { return }
            self.pizzas = pizzas!
            //print(self.pizzas)
            self.tableView.reloadData()
            //print(self.pizzas)
        }


    }   //end of viewDidLoad

    private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) {
        Alamofire.request("http://127.0.0.1:4000/inventory", method: .get)
            .validate()
            .responseJSON { response in
                guard response.result.isSuccess else { return completion(nil) }
                guard let rawInventory = response.result.value as? [[String: Any]?] else { return completion(nil) }
                let inventory = rawInventory.compactMap { pizzaDict -> Pizza? in
                    var data = pizzaDict!
                    data["image"] = UIImage(named: pizzaDict!["image"] as! String)

                    //print(data)
                    //print("CHECK")
                    print("Printing all data: ", Pizza(data: data))
                    //printing all inventory successful


                    return Pizza(data: data)
                }
                //self.tableView.reloadData()
                completion(inventory)
        }
    }

    @IBAction func ordersButtonPressed(_ sender: Any) {
        performSegue(withIdentifier: "orders", sender: nil)
    }

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

    //PRINTING ROWS 0 TWICE in console
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //print("ROWS", pizzas.count)
        return self.pizzas.count
    }


    //THIS IS WHERE THE CELL IDENTIFIER IS ??
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //print("IN CELLFORROWAT")

        tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "cell")

        let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PizzaTableViewCell

        //cell.backgroundColor = Services.baseColor

        cell.name?.text = pizzas[indexPath.row].name
        cell.imageView?.image = pizzas[indexPath.row].image
        cell.amount?.text = "$\(pizzas[indexPath.row].amount)"
        cell.miscellaneousText?.text = pizzas[indexPath.row].description

        print(cell.name?.text! as Any)
        print(cell.imageView as Any)
        //print("END CELLFORROWAT")

        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }  //END OF

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "pizza", sender: self.pizzas[indexPath.row] as Pizza)
    }  //END OF override func tableView

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "pizza" {
            guard let vc = segue.destination as? PizzaViewController else { return }
            vc.pizza = sender as? Pizza
        }
    }  //END OF override preppare func

}
class PizzaTableViewCell: UITableViewCell {

    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var pizzaImageView: UIImageView!
    @IBOutlet weak var amount: UILabel!

    @IBOutlet weak var miscellaneousText: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

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

         //Configure the view for the selected state
    }

}
struct Pizza {
    let id: String
    let name: String
    let description: String
    let amount: Float
    let image: UIImage

    init(data: [String: Any]) {

        //print("CHECK:: pizza.swift")

        self.id = data["id"] as! String
        self.name = data["name"] as! String

//        self.amount = data["amount"] as! Float
        self.amount = ((data["amount"] as? NSNumber)?.floatValue)!

        self.description = data["description"] as! String
        self.image = data["image"] as! UIImage
    }

}

我还打印了数组的值到控制台,数据按预期打印,但 cell.name?.textcell.amount?.text 的值, 和 cell.miscellaneousText?.text 打印 nil。

最佳答案

请尝试在您作为参数传递给 fetchInventory 的代码中的主线程中重新加载您的 tableview:

DispatchQueue.main.async { 
    self.tableView.reloadData()
}

因此,您的 fetchInventory 调用应变为:

    fetchInventory { pizzas in
        guard pizzas != nil else { return }
        self.pizzas = pizzas!
        //print(self.pizzas)
        DispatchQueue.main.async { 
            self.tableView.reloadData()
        }
        //print(self.pizzas)
    }

请避免从后台线程执行 UI 工作,因为它不正确/不安全。另外,您也可以尝试在该主线程 block 内设置 self?.pizzas 。 请考虑 Alan 关于双重调用的建议。

  1. 请从 tableView/cellForRow 中完全删除 register。

    // tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "cell")
    
  2. 代替:

    cell.imageView?.image = pizzas[indexPath.row].image
    

    放:

    cell.pizzaImageView?.image = pizzas[indexPath.row].image
    

这是您的商店名称。

请检查我下面的测试是否有效 :

import UIKit

类 PizzaListTableViewController: UITableViewController {

var pizzas: [Pizza] = []

override func viewDidLoad() {
    super.viewDidLoad()
    //title you will see on the app screen at the top of the table view
    navigationItem.title = "Drink Selection"

    //tableView.estimatedRowHeight = 134
    //tableView.rowHeight = UITableViewAutomaticDimension

    fetchInventory { pizzas in
        guard pizzas != nil else { return }
        self.pizzas = pizzas!
        print(self.pizzas)
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
        //print(self.pizzas)
    }
}   //end of viewDidLoad

private func fetchInventory(completion: @escaping ([Pizza]?) -> Void) {
    let rawInventory0 = [
        [
            "id": "1",
            "name": "name1",
            "amount": 1234,
            "description": "description1",
            "image": "image1"
        ],
        [
            "id": "2",
            "name": "name2",
            "amount": 1235,
            "description": "description2",
            "image": "image2"
        ],
        [
            "id": "3",
            "name": "name3",
            "amount": 1236,
            "description": "description3",
            "image": "image3"
        ],
        [
            "id": "4",
            "name": "name4",
            "amount": 1237,
            "description": "description4",
            "image": "image4"
        ]
    ]  as? [[String: Any]?]
    guard let rawInventory1 = rawInventory0 as? [[String: Any]?] else { return completion(nil) }
    let inventory = rawInventory1.compactMap { pizzaDict -> Pizza? in
        var data = pizzaDict!
        data["image"] = UIImage(named: pizzaDict!["image"] as! String)
        print(data)
        print("CHECK")
        print("Printing all data: ", Pizza(data: data))
        //printing all inventory successful
        return Pizza(data: data)
    }
    //self.tableView.reloadData()
    completion(inventory)
}

// MARK: - Table view data source

@IBAction func ordersButtonPressed(_ sender: Any) {
    performSegue(withIdentifier: "orders", sender: nil)
}

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

//PRINTING ROWS 0 TWICE in console
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //print("ROWS", pizzas.count)
    return self.pizzas.count
}


//THIS IS WHERE THE CELL IDENTIFIER IS ??
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //print("IN CELLFORROWAT")

    // tableView.register(PizzaTableViewCell.self, forCellReuseIdentifier: "cell")

    let cell: PizzaTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PizzaTableViewCell

    //cell.backgroundColor = Services.baseColor

    cell.name?.text = pizzas[indexPath.row].name
    cell.pizzaImageView?.image = pizzas[indexPath.row].image
    cell.amount?.text = "\(pizzas[indexPath.row].amount)"
    cell.miscellaneousText?.text = pizzas[indexPath.row].description

    print(cell.name?.text! as Any)
    //print(cell.imageView as Any)
    //print("END CELLFORROWAT")

    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100.0
}  //END OF

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "pizza", sender: self.pizzas[indexPath.row] as Pizza)
}  //END OF override func tableView

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "pizza" {
        guard let vc = segue.destination as? PizzaViewController else { return }
        vc.pizza = sender as? Pizza
    }
}  //END OF override preppare func

关于ios - 将数据从数组加载到 UITableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55525768/

有关ios - 将数据从数组加载到 UITableView 单元格的更多相关文章

  1. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  6. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  7. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  8. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  9. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  10. ruby - 在 Ruby 中用键盘诅咒数组浏览 - 2

    我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作

随机推荐