UItableview2--滑动到指定单元格,设置单元格间隔背景色

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if (cell == nil)
        {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        let rowNum = (indexPath as NSIndexPath).row
        //获取当前单元格,在段落中的行数
        cell?.textLabel?.text = months[rowNum]
        //根据单元格的行数,从数组中获取对应位置的元素,作为当前单元格的标题文字。
        return cell!
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let rect = CGRect(x: 0, y: 140, width: 320, height: 420)
        let tableView = UITableView(frame: rect)
        
        tableView.dataSource = self
        tableView.delegate = self
        
        //初始化一个索引路径对象,用来表示表格中的第一个段落和第十二行的位置
        let indexpath = IndexPath(row: 11, section: 0)
        //调用表格对象的滚动到指定位置的方法,滑动到指定的索引位置
        tableView.scrollToRow(at: indexpath, at: .top, animated: true)

在这里插入图片描述

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
            //创建一个字符串,作为单元格的复用标识符,并从所有已经开辟内存的单元格里面,选择一个具有同样标识符的,空闲的单元格。
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if (cell == nil)
            //如果在可重用使用的单元格队列中,没有可以重复使用的新的单元格,则创建新的单元格。新的单元格具有系统默认的单元格样式,并拥有一个复用标识符。
        {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        let rowNum = (indexPath as NSIndexPath).row
        //获取当前单元格,在段落中的行数
        cell?.textLabel?.text = "cell Item \(rowNum)\(months[rowNum])"
        //根据单元格的行数,从数组中获取对应位置的元素,作为当前单元格的标题文字。
        if (rowNum % 2 == 0)
        {
            cell?.backgroundColor = UIColor.purple
        }
        else
        {
            cell?.backgroundColor = UIColor.orange
        }
        return cell!
    }

标识符部分是重点

运行效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值