swift -> UICollectionView 网格布局(九宫格) 可 移动,删除

 

 

import UIKit

var itemWh:CGFloat = 0,itemHt:CGFloat = 75;

class ViewController:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{
    
    var data:[String] = [String]();
    
    let cellName:String = "MyCell";
    var myCollection : UICollectionView!
    
    var screenWh:CGFloat = 0;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        //
        screenWh = self.view.frame.width;
        //每行3个
        itemWh = screenWh/3
        
        data = [
            "a","b","c","d","e","f","g"
        ];
        
        //
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width:itemWh,height:itemHt)
        //列间距,行间距,偏移
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
        
        myCollection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
        myCollection.register(MyCell.self, forCellWithReuseIdentifier: cellName)
        myCollection.backgroundColor = UIColor.white
        myCollection.delegate = self
        myCollection.dataSource = self
        self.view.addSubview(myCollection)
        
        //添加拖动手势
        let gesture = UILongPressGestureRecognizer(target: self, action: #selector(viewCustom(_ :)))
        myCollection.addGestureRecognizer(gesture)
        
    }
    func viewCustom(_ longPress:UILongPressGestureRecognizer){
        let point:CGPoint = longPress.location(in: longPress.view)
        let indexPath = self.myCollection?.indexPathForItem(at: point)
        if(longPress.state == .began &&  indexPath == nil){return;}
        switch longPress.state {
        case .began:
            self.myCollection?.beginInteractiveMovementForItem(at: indexPath!)
            break
        case .changed:
            self.myCollection?.updateInteractiveMovementTargetPosition(point)
            break
        case .ended:
            self.myCollection?.endInteractiveMovement()
            break
        default:
            self.myCollection?.cancelInteractiveMovement()
            break
        }
        
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1;
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    //item 可以移动
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        return true;
    }
    //item 拖动结束时触发
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
        let sourceIndex = data[sourceIndexPath.row];
        data.remove(at: sourceIndexPath.row)
        data.insert(sourceIndex, at: destinationIndexPath.row)
        //myCollection.reloadData()
        print(data)
    }
    //点击执行删除
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        data.remove(at: indexPath.row)
        myCollection.deleteItems(at: [indexPath])
        print(data)
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cells = myCollection.dequeueReusableCell(withReuseIdentifier: cellName, for: indexPath) as! MyCell
        cells.logo.image = #imageLiteral(resourceName: "a0")
        cells.title.text = data[indexPath.row]
        return cells
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
}

class MyCell:UICollectionViewCell{
    var logo:UIImageView!
    var title:UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame);
        
        let imgWidth:CGFloat = 50;
        
        logo = UIImageView(frame: CGRect(x: (itemWh-imgWidth)/2, y: 5, width: imgWidth, height: imgWidth));
        logo.clipsToBounds = true
        logo.layer.cornerRadius = 2;
        logo.contentMode = .scaleAspectFill;
        title = UILabel(frame: CGRect(x: (itemWh-imgWidth)/2, y: 5+imgWidth, width: imgWidth, height: 18));
        title.textAlignment = .center
        title.font = UIFont.systemFont(ofSize: 16)
        title.textColor = UIColor.init(white: 0.3, alpha: 1)
        self.addSubview(logo)
        self.addSubview(title)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

  

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是用 Swift 编写的 UICollectionView 显示九宫格的代码: 首先,在 ViewController.swift 中添加以下代码: ``` import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { let reuseIdentifier = "cell" let items = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) layout.minimumLineSpacing = 10 layout.minimumInteritemSpacing = 10 layout.itemSize = CGSize(width: (view.frame.size.width - 30)/3, height: (view.frame.size.width - 30)/3) let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), collectionViewLayout: layout) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self view.addSubview(collectionView) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) cell.backgroundColor = UIColor.blue let label = UILabel(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height)) label.textAlignment = .center label.text = items[indexPath.row] label.textColor = UIColor.white cell.contentView.addSubview(label) return cell } } ``` 代码解释: - `UICollectionViewFlowLayout` 是集合视图的布局对象,用于设置集合视图的外观和布局。 - `UICollectionView` 是集合视图的视图对象,用于显示 客户端 端的 IU。我们注册了 UITableViewCell,在 cellForItemAt 方法中添加了数字标签,然后返回 UITableViewCell。 最后,我们运行代码,就可以看到一个显示九宫格的集合视图。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值