Xcode9学习笔记50 - 调整UITableView单元格的顺序

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {//表格视图数据源协议、表格视图代理协议
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]//创建数组作为表格的数据来源
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let rect = CGRect(x: 0, y: 40, width: 320, height: 420)//创建一个显示区域
        let tableView = UITableView(frame: rect)//初始化一个表格视图,并设置其位置和尺寸
        tableView.delegate = self//设置表格视图的代理为当前的视图控制器类
        tableView.dataSource = self//设置表格视图的数据源为当前的视图控制器类
        tableView.setEditing(true, animated: false)//在默认状态下开启表格的编辑模式
        self.view.addSubview(tableView)//将表格视图添加到当前视图控制器的根视图中
    }
    //添加一个代理方法,用来设置表格视图拥有的行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return months.count
    }
    //添加一个代理方法,用来初始化或复用表格视图中的单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"//创建一个字符串,作为单元格的复用标识符
        //单元格的标识符可以看作是一种复用机制,此方法可以从所有已经开辟内存的单元格里面,选择一个具有同样标识符的、空闲的单元格
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        //如果在可重用单元格队列中,没有可以重复使用的单元格,则创建新的单元格。新单元格拥有一个复用标识符
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: identifier)
        }
        let rowNum = indexPath.row//获取当前单元格在段落中的行数
        cell?.textLabel?.text = months[rowNum]
        return cell!//返回设置好的单元格对象
    }
    //添加一个代理方法,用来设置单元格的编辑模式
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.none
    }
    //添加一个代理方法,用来设置单元格是否允许拖动换行
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    //添加一个代理方法,用来响应单元格的移动事件
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let fromRow = sourceIndexPath.row//获取单元格移动前的位置
        let toRow = destinationIndexPath.row//获取单元格移动后的位置
        let obj = months[fromRow]//获得数组在单元格移动前的对象
        months.remove(at: fromRow)//删除数组中单元格移动前位置的对象
        months.insert(obj, at: toRow)//然后在数组中的目标位置重新插入一份删除的对象,以同步数据源,并保证数据与界面的一致性
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值