首页 > 解决方案 > 如何在 tableview Swift 中获取选中标记的行列表?

问题描述

我启用了多行选择,并且能够在用户触摸特定单元格时添加复选标记。现在最后,我想查看哪些行被选择并根据行号执行操作。如何获取这些行详细信息/数字?谢谢!

用于选择/取消选择行的代码:

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        main_table.reloadData()
        self.main_table.allowsMultipleSelection = true
        self.main_table.allowsMultipleSelectionDuringEditing = true
    }

然后在单元控制器中:

 override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        accessoryType = selected ? UITableViewCell.AccessoryType.checkmark : UITableViewCell.AccessoryType.none
    }

标签: iosswiftuitableview

解决方案


首先,避免使用下划线(_)符号来声明Swift中的变量。而是使用驼色套管

@IBOutlet weak var mainTable: UITableView!

接下来,要仅获取rows中选定indexPathstableView,请使用indexPathsForSelectedRowsmap(_:)

if let selectedRows = self.tableView.indexPathsForSelectedRows?.map({ $0.row }) {
    print(selectedRows)
}

由于indexPathsForSelectedRows返回Optional arrayof IndexPath,您需要将其解包以获取值。


推荐阅读