UICollectionView--九宫格

博客介绍了如何利用UICollectionView在iOS应用中实现九宫格布局。内容提到了UICollectionView与UITableView的区别,强调在UICollectionView中设计item的重要性,并指出需要自定义UICollectionViewCell来包含显示元素,如UILabel。同时,注册cell和实现相关方法是实现九宫格的关键步骤。
摘要由CSDN通过智能技术生成

它是苹果提供的一种瀑布流效果
它与tableView相似,但是UICollectionView中我们设计的是他的Item,它用item进行显示, 它可以等于cell的大小,但是cell不能够等于他的大小,

    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout alloc]init];
//设计item大小
    flowLayout.itemSize = CGSizeMake(200,160);
//设置行间距
    flowLayout.minimumLineSpacing = 2;
//设置列间距
    flowLayout.minmumInteritrmSpacing = 2;
//设置滚动方式,默认是垂直方向
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//创建一个collect
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值