保存多个选定UITableViewCell值的数组

时间:2018-02-17 20:25:25

标签: ios arrays swift uitableview

使用Table View(XCode 9,Swift 4)时,我遇到了一个非常具体的问题。我想要做的是,创建一个名为 foodDetailInfoArray 的数组,其中包含用户手动选择的表格单元格中 foodName 标签的文本值。目前,虽然 .setSelected 方法可以根据需要更改单元格的UI,但它无法帮助我正确记录 foodName.text 值。问题是即使在滚动表视图时也会记录文本值,并且数组值也会被替换。下面是代码和打印输出的样本。

var foodDetailInfoArray: [String] = []

@IBOutlet var unselectedCell: UIView!
@IBOutlet var foodName: UILabel!
@IBOutlet var carbonValue: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
    if selected == true {
        self.unselectedCell.backgroundColor = UIColor.init(red: 4/255, green: 206/255, blue: 132/255, alpha: 1)
        self.foodName.textColor = UIColor.white
        self.carbonValue.textColor = UIColor.white
        foodDetailInfoArray.append(foodName.text!)
    } else {
        self.unselectedCell.backgroundColor = UIColor.clear
        self.foodName.textColor = UIColor.black
        self.carbonValue.textColor = UIColor.black
    }

    print(foodDetailInfoArray)
}

print语句给了我这样的结果: (这是当单元格甚至没有被选中时,我只是滚动表格视图。)

["pepper"]
["pasta"]
["pasta", "pepper"]
["pepper"]
["pepper", "pasta"]
["stir-fry"]
["stir-fry", "stir-fry"]
["vegetable"]
["vegetable", "vegetable"]

然而,我理想的是(按照包含给定foodName的单元格的顺序):

["pasta"]
["pasta", "pepper"]
["pasta", "pepper", "tomato"]
["pasta", "pepper", "tomato", "stir-fry"]

如果取消选择某个单元格,则必须删除该名称,即如果取消选择了tomato,则数组将为

["pasta", "pepper", "stir-fry"]

......等等

PS:我不是专业的程序员,最近也是自学成才的,所以如果问题不清楚,请告诉我。

2 个答案:

答案 0 :(得分:4)

我会通过视图控制器处理单元格的选择和取消选择,这样您也可以更好地使用foodDetailInfoArray。在answer的帮助下,您可以这样做:

import UIKit

class ViewController: UITableViewController {

    // example data
    let names = [ "pepper", "pasta", "stir-fry", "vegetable"]

    var foodDetailInfoArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // allow multiselection
        tableView.allowsMultipleSelection = true
    }


    // MARK: UITableViewDataSource

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = names[indexPath.row]
        // Don't show highlighted state
        cell.selectionStyle = .none

        return cell
    }

    // MARK: UITableViewDelegate

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // also do your UI changing for the cell here for selecting

        // Add your food detail to the array
        foodDetailInfoArray.append(names[indexPath.row])
    }

    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        // also do your UI changing for the cell here for deselecting

        // Remove your food detail from the array if it exists
        if let index = foodDetailInfoArray.index(of: names[indexPath.row]) {
            foodDetailInfoArray.remove(at: index)
        }
    }

}

<强>结果

enter image description here

答案 1 :(得分:2)

我会为didSelectRowAtIndexPath尝试委托方法tableViews。让您的视图控制器采用UITableViewDelegate协议并执行以下操作。

假设您有一个foods数组,以及一个最初为空的foodsSelected数组。

let foods:[String] = ["Apples","Avocado","Bananas"]
var foodsSelected:[String] = []

现在,只要选择了一个单元格,就会调用此委托方法,并从foodsSelected数组中添加或删除所选的食物。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Check if the selected food is in the foodsSelect array
    if(!foodsSelected.contains(foods[indexPath.row])){
        //If it's not, append it to the array
        foodsSelected.append(foods[indexPath.row])
    }else{
        //If it is, remove it from the array. 
        //Note there are many ways to remove an element from an array; I decided to use filter. 
        foodsSelected = foodsSelected.filter({$0 != foods[indexPath.row]})
    }
    print(foodsSelected)
}

以下是按顺序选择这些项目时的输出:ApplesAvocadoBananasAvocado

["Apples"]
["Apples", "Avocado"]
["Apples", "Avocado", "Bananas"]
["Apples", "Bananas"]