美文网首页
swift tableviewCell 删除 和cell的移动

swift tableviewCell 删除 和cell的移动

作者: 至尊宝_4233 | 来源:发表于2021-09-10 10:07 被阅读0次
满足移动cell和删除cell的需求
///这里的数据源使用的可变数组,主要是为了使用exChange循环方法
var cellArr = NSMutableArray()

override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()  //这里是简单创建一个tableview
        cellArr = ["第一行","第二行","第三行","第四行","5","6","7","8","9","10"]
    }
实现tableview的代理方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? transverseCell
        
        cell?.lab.text = cellArr[indexPath.row] as? String
        cell?.backgroundColor = UIColor(red: (CGFloat(Float(arc4random()%255)/255.0)), green: (CGFloat(Float(arc4random()%255)/255.0)), blue: (CGFloat(Float(arc4random()%255)/255.0)), alpha: 1.0)

        return cell ?? transverseCell.init()
    }

下面需要用到几个tableview的代理方法实现移动

///下面两个方法是移动cell的
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        cellArr.exchangeObject(at: (sourceIndexPath as NSIndexPath).row, withObjectAt: (destinationIndexPath as NSIndexPath).row)
    }
///下面三个方法,是删除cell用的
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            cellArr.removeObject(at: indexPath.row)
            table.deleteRows(at: [indexPath], with: .automatic)
        }
    }

这里最好是用swift里的array数组去完成,目前我就讨巧使用了OC的可变数组。

相关文章

网友评论

      本文标题:swift tableviewCell 删除 和cell的移动

      本文链接:https://www.haomeiwen.com/subject/klpgwltx.html