首页 > 解决方案 > 在 UITableView 中至少选择一行

问题描述

嗨,有一个 UITableView 可以选择选中/取消选中每一行。它工作正常,不,我想确保至少选择了一行,并且当用户尝试取消选中时,向他显示必须选择至少一个选项的警报。我该如何实施?

这是当前代码

private var locationToDisplay = [Location]();
override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.dataSource=self
    self.tableView.delegate=self
    self.tableView.allowsMultipleSelection = true
}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "SubscriptionCell", for: indexPath) as! SubscriptionTableViewCell
    let cellLocation = locationToDisplay[indexPath.row]
    cell.labelLocation.text = cellLocation.location_name

    if cellLocation.subscribed == 1 {
        self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    } else {
        self.tableView.deselectRow(at: indexPath, animated: false)
    }
    return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       locationToDisplay[indexPath.row].subscribed = 1
}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if (countSelections()==1) {
        //Last checked item
    }

       locationToDisplay[indexPath.row].subscribed = 0
}

func countSelections()->Int {
    var count: Int = 0
    for location in locationToDisplay {
        if (location.subscribed == 1) {
            count = count + 1
        }
    }
    return count
}

标签: iosswiftuitableview

解决方案


查看func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath?委托方法。如果您不希望用户实际取消选择该行,您可以在此处返回 nil(然后您也可以显示警报)。

(此外,您不应该在方法中调用self.tableView.selectRowself.tableView.deselectRowcellForRowAt方法中调用。请查看https://stackoverflow.com/a/13827975/403425以获得更多帮助。)


推荐阅读