使用ListView的最佳方式

时间:2017-08-20 10:17:16

标签: ios swift

嘿伙计们我现在正在学习swift,我尝试编写一个游戏。我想显示包含这些项目的项目和不同属性的列表。 所以首先我有用户选择他们可以选择食物或玩具或未来的其他东西。在这里,我尝试只做一个ViewController并根据选择更改内部的东西。现在我将这些项目放在一个类的数组中。 它们看起来像这样:

    class FoodData {
    var name: String
    var description = "Basic Food"
    var owned = 0
    var taste = 0
    var price = 0
    var water = 0
    var image = "default.png"
    init(name: String){
    self.name=name
    }
}
class ToyData {
    var name: String
    var description = "Basic Item"
    var owned = 0
    var price = 0
    var joy = 0
    var image = "default.png"
    init(name: String){
    self.name=name
    }
}

我用以下内容初始化:

    var foodLoad=[FoodData]() 

    func loadFoodData(){
    foodLoad.append(FoodData(name: "IceCream"))
    foodLoad[0].description="Very Cold"
    foodLoad[0].owned=10
}

玩具的风格相同。现在我在两个Arrays中有两个类,名为foodLoad [i]和toyLoad [I]

对于表视图,我用协议填写

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let shopCell = tableView.dequeueReusableCell(withIdentifier: shopCellIdentifier, for: indexPath) as! ShopCellStyle

    shopCell.shopNameLabel?.text = shopData[indexPath.row].name
    shopCell.shopImageView?.image = UIImage(named: shopData[indexPath.row].image)
    shopCell.shopPriceLabel?.text = String(shopData[indexPath.row].price) + currency
    return shopCell

所以我的想法是用User选项分配shopData。 但是如果我分配shopData = foodLoad,我就不能再将它改为toyLoad了。所以也许你可以给我一个如何以最佳方式解决这个问题的提示。

1 个答案:

答案 0 :(得分:0)

表示你的cellForRowAt indexPath:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let shopCell = tableView.dequeueReusableCell(withIdentifier: "shopCellIdentifier", for: indexPath) as! ItemCell

    if selection == "food" {
        shopCell.shopNameLabel?.text = foodLoad[indexPath.row].name
        shopCell.shopImageView?.image = UIImage(named: 
        foodLoad[indexPath.row].image)
        shopCell.shopPriceLabel?.text = String(foodLoad[indexPath.row].price) + currency
    } 
    else if selection == "toys" {
        shopCell.shopNameLabel?.text = toyLoad[indexPath.row].name
        shopCell.shopImageView?.image = UIImage(named: 
        toyLoad[indexPath.row].image)
        shopCell.shopPriceLabel?.text = String(toyLoad[indexPath.row].price) + currency
   }
   return shopCell
}

您还需要numberOfRowsInSection UITableView功能。当用户更改类型选择时调用tableview.reloadData()。

相关问题