ios - 选择 UITableView 中的所有行,并在数组中附加标签

标签 ios arrays swift uitableview

我可以在点击按钮时选择所有行,但是我想将该行中的标签添加到我的数组中并将其删除 我能够在 didSelectRowAt 和“didDeselectRowAt”中分别添加和删除来实现这一点! 我正在使用的代码在 TableView 函数之外。

func selectAllRows()
{
    for section in 0..<tableView.numberOfSections
    {
        for row in 0..<tableView.numberOfRows(inSection: section)
        {
            tableView.selectRow(at: IndexPath(row: row, section: section), animated: false, scrollPosition: .none)
            let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as? CheckableTableViewCell
            classesArray.append((cell?.textLabel?.text)!)
        }
    }
}

最佳答案

let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) as? CheckableTableViewCell

这导致了一个问题,因为 cell 可能是 nil。 请参阅 func cellForRow(at indexPath: IndexPath) -> UITableViewCell? 的文档

Return Value
An object representing a cell of the table, or nil if the cell is not visible or indexPath is out of range

不要依赖 UI,要依赖你的模型。 在 tableView(_ tableView:, cellForRowAt:) 中,您可以:

let classess = classes[indexPath.row]["classes"] as? String ?? "" 
let sections = classes[indexPath.row]["section"] as? String ?? ""
cell.textLabel?.text = "(classess) - (sections)" 

只需为 classesArray.append((cell?.textLabel?.text)!) 做同样的事情:

classesArray.append("(classess) - (sections)") //recalculate it like before

关于ios - 选择 UITableView 中的所有行,并在数组中附加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50890254/

相关文章:

ios - Facebook iOS 移动 Web JS SDK 错误

c - 变量周围的运行时检查失败堆栈已损坏

java - 如何打印ArrayList中的元素内容?

php - 如何遍历嵌套数组?

ios - CGAffineTransform:同时应用平移和缩放

ios - hidesBarsOnSwipe 禁用左右滑动手势

ios - Xcode Interface Builder 高度/宽度设置与 View Controller

iphone - iOS UITableview隐藏分隔线

ios - 根据键的值从 NSDictionary 的 NSMutableArray 中删除重复项

ios - 在ios swift中实现地址搜索