简体   繁体   English

如何从多个选定的行中获取数据并在另一个VC tableview单元格Swift4中显示

[英]How to get data from the multiple selected rows and show in another VC tableview cell Swift4

Hello I am trying to complete my task since 2 days but still no success searched everywhere , I want to select multiple rows from tableview cells (which contains 2 labels and one image) then I want to transfer into another vc and show in tableview , I am able to select multiple rows and get this type index from selected rows but now I don't know how to get data and transfer into another vc and show in table view please help I am getting selected rows index like this [[0, 1], [0, 2], [0, 3] 您好,我试图从2天开始完成任务,但是到处都找不到成功,我想从tableview单元格中选择多行(其中包含2个标签和一个图像),然后我想转移到另一个vc中并在tableview中显示,我能够选择多个行并从选定的行中获取此类型索引,但是现在我不知道如何获取数据并将其传输到另一个vc中并在表视图中显示,请帮助我获取这样的选定行索引[[0,1 ],[0、2],[0、3]

VC Code VC代码

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {


    @IBOutlet weak var tableview: UITableView!


    var labone = ["1","2","3","4","5","6"]
    var labtwo = ["a","b","c","d","e","f"]
    var img =  ["bag","bag","bag","bag","bag","bag"]


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func button(_ sender: Any) {

        let selectedindexPath = tableview.indexPathsForSelectedRows
        if(selectedindexPath != nil){
            let toy  = labone[0]
            print(toy)
            print(selectedindexPath) }

        else{
            print("null")
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return labone.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

         let name = cell.viewWithTag(1) as! UILabel
        let name_two = cell.viewWithTag(2) as! UILabel
        let imgg = cell.viewWithTag(3) as! UIImageView

        name.text = labone[indexPath.row]
        name_two.text = labtwo[indexPath.row]
        imgg.image = UIImage(named: img[indexPath.row])


        return cell

    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
        cell.contentView.backgroundColor = UIColor.yellow

    }


    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        // let selectedCell = tableview.cellForRow(at: indexPath)
        if let label = cell?.contentView.viewWithTag(4) as? UIImageView {
            label.image = UIImage(named: "check_disable")
        }

    }

}

As @Rakshith suggest in their comment, move your data (labone, labtwo, img arrays) out of the view controller and into a model object. 就像@Rakshith在他们的评论中建议的那样,将数据(labone,labtwo,img数组)移出视图控制器,然后移入模型对象。 Pass that model object to your second view controller. 将该模型对象传递给第二个视图控制器。

Also create an array selectedIndexPaths in your second view controller. 还要在第二个视图控制器中创建一个数组selectedIndexPaths When you tap the button in your ViewController , get the array of selected index paths and pass it to your second view controller. 当您点击ViewController的按钮时,获取选定索引路径的数组并将其传递给第二个视图控制器。

In your second view controller's viewWillAppear , use the selectedIndexPaths variable to copy the items selected items into an array itemsToDisplay and use that in your table view data source methods to populate the second view controller's table view. 在第二个视图控制器的viewWillAppear ,使用selectedIndexPaths变量将所选项目复制到数组itemsToDisplay中,并在表视图数据源方法中使用该变量填充第二个视图控制器的表视图。

You should use some structure like below and then update the state of item selected or deselected then when you want to go to next viewController you can filter your dataSource with the items selected like below, 您应该使用如下所示的某种结构,然后更新所选或取消选中的项目的状态,然后当您要转到下一个viewController时,可以使用以下所选的项目过滤dataSource,

 class CellModel {

    var labelOne: String
    var labelTwo: String
    var imageName: String
    var isSelected = false

    init(_ labelOne: String, labelTwo: String, imageName: String) {
        self.labelOne = labelOne
        self.labelTwo = labelTwo
        self.imageName = imageName
    }
}

Update your viewController, 更新您的viewController,

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

   let dataSource = [CellModel("1", labelTwo: "a", imageName: "bag"),
                     CellModel("2", labelTwo: "b", imageName: "bag"),
                     CellModel("3", labelTwo: "c", imageName: "bag"),
                     CellModel("4", labelTwo: "d", imageName: "bag"),
                     CellModel("5", labelTwo: "e", imageName: "bag"),
                     CellModel("6", labelTwo: "f", imageName: "bag")]
}

then you can update your cellForRowAt like below, 然后您可以像下面那样更新cellForRowAt,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

       let name = cell.viewWithTag(1) as! UILabel
       let name_two = cell.viewWithTag(2) as! UILabel
       let imgg = cell.viewWithTag(3) as! UIImageView

       let model = self.dataSource[indexPath.row]
       name.text = model.labelOne
       name_two.text = model.labelTwo
       imgg.image = UIImage(named: model.imageName)

       return cell
    }

update the numberOfRowInSection with this 使用此更新numberOfRowInSection

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

and you can update the state of model when cell is selected/deseleced like this, 这样,您可以在选择/删除单元格时更新模型的状态,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
        cell.contentView.backgroundColor = UIColor.yellow
        self.dataSource[indexPath.row].isSelected = true
    }


    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        // let selectedCell = tableview.cellForRow(at: indexPath)
        if let label = cell?.contentView.viewWithTag(4) as? UIImageView {
            label.image = UIImage(named: "check_disable")
            self.dataSource[indexPath.row].isSelected = false
      }
 }

and finally in button action you can filter the selected models and pass to next viewController 最后在按钮操作中,您可以过滤选定的模型并传递到下一个viewController

@IBAction func button(_ sender: Any) {

     let selectedItems = self.dataSource.filter({ $0.isSelected == true })
     // Pass to next ViewController the selectedItmes
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM