美文网首页
swift-自定义cell和使用xibCell创建colleti

swift-自定义cell和使用xibCell创建colleti

作者: money_ac9e | 来源:发表于2018-08-25 11:54 被阅读0次

    collection view的简单使用

    1.创建collection view

    var collection : UICollectionView? = nil
    

    创建collectionview

    let layout = UICollectionViewFlowLayout()
    self.collection = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), collectionViewLayout: layout)
    self.collection?.delegate = self;
    self.collection?.dataSource = self;
    self.collection?.backgroundColor = UIColor.white
    self.view.addSubview(self.collection!)
    

    这里注意layout的创建,创建错误会出现不走代理的问题

    2.声明代理

    class BaseViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
    

    这和OC中不同,直接在class中声明就行

    3.常用的方法

    // MARK: - collection
        override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 8
        }
        override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
            cell.backgroundColor = UIColor.init(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1)
            cell.titleLable.text = "逗比"
            cell.titleView.backgroundColor = UIColor.init(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1)
            return cell
        }
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: CGFloat(kScreenWidth-45)/3.0, height: 50)
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
            return UIEdgeInsetsMake(10, 10, 10, 10)
        }
        
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            print(indexPath.row)
        }
    

    4.

    使用纯代码创建cell

    self.collection?.register(TestCollectionViewCell.self, forCellWithReuseIdentifier: "TestCollectionViewCell")
    

    使用xib创建cell

    self.collection?.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell")
    

    demo下载

    相关文章

      网友评论

          本文标题:swift-自定义cell和使用xibCell创建colleti

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