【问题标题】:append tableview cell text label into a empty array将 tableview 单元格文本标签附加到空数组中
【发布时间】:2020-12-28 13:19:15
【问题描述】:

我想获取 tableview 单元格上显示的所有索引路径整数。现在,单元格上有数字 1-5。这就是应该附加到数组emptyA的内容。我试图在索引路径上进行压缩,但这不起作用。我所有的代码都在下面没有使用情节提要。代码应该在视图中附加数组确实加载。

   import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    var emptyA = [Int]()
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text =    "\([indexPath.row+1])"
     
        return cell
    }
    
    var theTable = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(theTable)
        theTable.frame = CGRect(x: 100, y: 100, width: 100, height: 300)
        theTable.delegate = self
        theTable.dataSource = self
        theTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        //need this part
        emptyA.append()
        
    }


}

【问题讨论】:

  • 硬编码项目数时,最简单的形式是emptyA = (0..<5).map{$0+1}。索引路径数组的作用是什么?

标签: arrays swift uitableview append indexpath


【解决方案1】:

您可以在emptyA 中添加indexPath.row tableView(_:cellForRowAt:) 方法,即

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = "\([indexPath.row+1])"
    if !emptyA.contains(indexPath.row+1) {
        emptyA.append(indexPath.row+1)
    }
    return cell
}

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多