返回 导航

Swift

hangge.com

Swift - 使用网格(UICollectionView)进行流布局

作者:hangge | 2015-02-06 11:06
(本文代码已升级至Swift4)

一、网格UICollectionView最典型的例子是iBooks。其主要属性如下:

1,layout
该属性表示布局方式,有Flow、Custom两种布局方式。默认是Flow流式布局。

2,Accessories
是否显示页眉和页脚

3,各种尺寸属性
Cell Size:单元格尺寸
Header Size:页眉尺寸
Footer Size:页脚尺寸
Min Spacing:单元格之间间距
Section Insets:格分区上下左右空白区域大小。

二、流布局的简单样例

1,先创建一个应用Simple View Application,在 StoryBoard 中删除默认的 View Controller,拖入一个 Collection View Controller 到界面上,这时我们可以看到已经同时添加了 Collection View Collection View Cell 控件。

2,勾选 Collection View Controller 属性面板里的 Is Initial View Controller 复选框,设置为启动视图控制器。

3,在 Collection View Cell里拖入一个Image ViewLabel并摆放好位置和大小,用于显示图标和名称。

4,设置Image Viewtag1Labeltag2Colletion View CellIdentifierDesignViewCell

5,最后,将 Collection View Controller Custom Class 设置成 ViewControllerViewController.swift 里面代码可以先改,具体见下方)

效果图如下:
 
--- ViewController.swift ---
import UIKit

class ViewController: UICollectionViewController {
    
    //课程名称和图片,每一门课程用字典来表示
    let courses = [
        ["name":"Swift","pic":"swift.png"],
        ["name":"OC","pic":"oc.jpg"],
        ["name":"java","pic":"java.png"],
        ["name":"php","pic":"php.jpeg"]
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 已经在界面上设计了Cell并定义了identity,不需要注册CollectionViewCell
        //self.collectionView.registerClass(UICollectionViewCell.self,
        //  forCellWithReuseIdentifier: "DesignViewCell")
        
        self.collectionView?.backgroundColor = UIColor.white
    }
    
    // CollectionView行数
    override func collectionView(_ collectionView: UICollectionView,
                                 numberOfItemsInSection section: Int) -> Int {
        return courses.count;
    }
    
    // 获取单元格
    override func collectionView(_ collectionView: UICollectionView,
                cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // storyboard里设计的单元格
        let identify:String = "DesignViewCell"
        // 获取设计的单元格,不需要再动态添加界面元素
        let cell = (self.collectionView?.dequeueReusableCell(
            withReuseIdentifier: identify, for: indexPath))! as UICollectionViewCell
        // 从界面查找到控件元素并设置属性
        (cell.contentView.viewWithTag(1) as! UIImageView).image =
            UIImage(named: courses[indexPath.item]["pic"]!)
        (cell.contentView.viewWithTag(2) as! UILabel).text =
            courses[indexPath.item]["name"]
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}


源码下载hangge_ CollectionView.zip
评论

全部评论(12)

回到顶部