iOS开发Swift-UITableView-func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"    //cell的ID
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid)  //对cell赋值
        if cell==nil {  //判断cell是否为空
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid)
        }
        
        cell?.textLabel?.text = "这个是标题~"   //标题赋值
        cell?.detailTextLabel?.text = "这里是内容了油~"   //内容赋值
        cell?.imageView?.image = UIImage(named:"Expense_success")  //图标赋值
        return cell!  //返回cell
    }

 返回一个被强制解包的cell.

含义:对cell及cell中的内容进行配置.初始化和复用指定索引位置的UITableViewCell必须实现.

当 UITableView 需要显示新的行时,它会自动调用这个方法。你可以在这个方法中为 cell 设置各种属性,比如文本、图片等。

这个方法有两个参数:

  1. tableView:这个参数是一个 UITableView 对象,表示这个 cell 所属的表格视图。
  2. indexPath:这个参数是一个 IndexPath 对象,表示这个 cell 在表格视图中的位置。

你需要根据 indexPathrowsection 属性来决定如何设置 cell。比如,如果你的表格有多个部分,并且每个部分都有多个行,你可能需要根据 sectionrow 的值来从数据源中获取不同的数据。

这个方法需要返回一个 UITableViewCell 对象。你可以从 UITableView 的复用队列中 dequeue 一个已经存在的 cell,也可以创建一个新的 cell。dequeue 的好处是可以提高性能,因为不需要每次都创建新的 cell。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell  
    cell.textLabel?.text = "Row \(indexPath.row)"  
    return cell  
}

 

例如:

 

posted @ 2023-09-18 15:21  临易  阅读(34)  评论(0编辑  收藏  举报