indexPath.row 始终为 0

objective

1个回答

写回答

isdy

2025-06-26 08:10

+ 关注

Swift
Swift

根据您提供的信息,我生成了一篇文章,以下是文章的案例代码和分段。

Swift

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

// 定义数据源

let data = ["苹果", "香蕉", "橙子", "西瓜", "葡萄"]

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

return data.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

cell.textLabel?.text = data[indexPath.row]

return cell

}

override func viewDidLoad() {

super.viewDidLoad()

let tableView = UITableView(frame: view.bounds, style: .plAIn)

tableView.dataSource = self

tableView.delegate = self

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

view.addSubview(tableView)

}

}

实现UITableView的数据源方法

在上述代码中,我们创建了一个ViewController类,并在其中实现了UITableViewDataSource和UITableViewDelegate协议。我们使用了一个字符串数组data作为数据源,其中包含了一些水果的名称。

在tableView(_:numberOfRowsInSection:)方法中,我们返回了数据源中元素的个数,这决定了表格视图中显示的行数。

在tableView(_:cellForRowAt:)方法中,我们为每一行创建了一个UITableViewCell对象,并将对应位置的水果名称赋值给了textLabel属性。最后,我们返回了这个单元格以供显示。

在viewDidLoad()方法中,我们创建了一个UITableView对象,并将其添加到了视图中。我们还设置了数据源和代理为当前的ViewController实例,并注册了一个标识符为"Cell"的单元格类。

通过以上的代码,我们实现了一个简单的表格视图,并显示了水果的名称。

希望以上的解释对您有所帮助。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号