Swift实现最简单的UICollectionView

作者: brycegao | 来源:发表于2017-03-24 11:58 被阅读257次

    UICollectionView可以实现表格布局、流式布局等, 跟UITableView很像。
    UICollectionView的布局方式分为Flow和Custom, 默认是Flow流式布局。
    尺寸属性:
    1、 Cell Size: 单元格大小
    2、Header Size: 页眉大小 (可以实现类似于Android ListView的headerview)
    3、Footer Size: 页脚大小 (可以实现类似于Android ListView的footerview)
    4、 Min Spacing: 单元格间距
    5、Section Insets: 分区间空白区域大小

    下面讲一下UICollectionView最简单的实现方式:
    1、 打开Main.storyboard, 选中Xcode右下角的UICollectionViewController并拖动到storyboard里;
    2、 选中UICollectionView并修改Identifier为“simpleCell” (说明:可以随意命名,在代码里通过这个字符串查找复用的cell);


    pic1.png

    3、 为了显示效果在Cell里添加UIImageView和UILable, 并设置UIImageView的tag为1、UILable的tag为2(从而在代码里能够找到引用); tag是整型,范围是1~1000。


    pic2.png
    4、拖动一个UIBarButtonItem到左上角,设置父窗口和子窗口的传值StorySegue, 在父界面Controller里添加点击事件函数,函数必须只有一个UIStoryBoradSegue类型。
    <pre>
    @IBAction func unwindToMain(_ segue: UIStoryboardSegue) {
    print("unwindToMain 子界面返回数据")

    //如果是从简单列表界面返回,拿到子窗口对象并取值; 类似于Android从intent里拿数据
    if let controller = segue.source as? SimpleController {
    let result = controller.result //模拟返回值
    print("子界面返回值:(result), 执行当前界面逻辑,如刷新界面等")
    }
    }</pre>
    选中左上角的UIBarButtonItem到左边的Exit选项或者上面的红色图标, 然后选中unwindToMain方法(注意:必须先定义这个函数,函数名可以随便命名,但函数必须只有一个UIStoryBoardSegue参数且添加@IBAction前缀)。


    方法1.png 方法2.png

    5、添加点击事件并选中show, 在代码里覆盖prepare函数(打开UIViewController前执行), unwind函数(子窗口返回值处理函数,类似于Android的onActivityResult函数), 为子窗口赋值(要显示的数据)。

    父窗口打开子窗口.png

    <pre>
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("prepare")
    if let des = segue.destination as? SimpleController { //判断要打开的界面
    //如果要打开的是最简单列表
    des.data = "最简单CollectionView" //向子窗口传递数据

            //name是标题, pic是要显示的图标
            let resources = [
                ["name": "厂商", "pic": "联系盟商"],
                ["name": "设置", "pic": "设置"],
                ["name": "提现", "pic": "提现"],
                ["name": "通知", "pic": "通知"],
                ["name": "camera", "pic": "camera"]
            ]
            des.resources = resources   //子界面要显示的数据
        }
    }
    

    </pre>

    效果图:


    效果图.png

    父窗口代码:
    <pre>
    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if let des = segue.destination as? SimpleController {   //判断要打开的界面
            //如果要打开的是最简单列表
            des.data = "最简单CollectionView"   //向子窗口传递数据
           
            //name是标题, pic是要显示的图标
            let resources = [
                ["name": "厂商", "pic": "联系盟商"],
                ["name": "设置", "pic": "设置"],
                ["name": "提现", "pic": "提现"],
                ["name": "通知", "pic": "通知"],
                ["name": "camera", "pic": "camera"]
            ]
            des.resources = resources   //子界面要显示的数据
        }
    }
    
    override func unwind(for unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
        print("unwind")
    }
    
    //子窗口返回数据。 先在父窗口添加点击事件,然后在storyboard里设置exit事件。 类似于Android的onActivityResult
    @IBAction func unwindToMain(_ segue: UIStoryboardSegue) {
        print("unwindToMain 子界面返回数据")
        
        //如果是从简单列表界面返回,拿到子窗口对象并取值; 类似于Android从intent里拿数据
        if let controller = segue.source as? SimpleController {
            let result = controller.result   //模拟返回值
            print("子界面返回值:\(result), 执行当前界面逻辑,如刷新界面等")
        }
    }
    

    }
    </pre>

    子窗口代码:
    <pre>
    //从资源里拖出的UICollectionViewController
    //UITableView和UICollectionView使用方法类似
    class SimpleController: UICollectionViewController {
    var data: String? //测试传值
    var result: String? //测试返回值

    //name是标题, pic是要显示的图标
    var resources: [[String:String]]?    //要显示的数据
    
    //设置标题栏背景, 只对当前界面生效
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return UIStatusBarStyle.lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print("父界面传值: \(data)")
        
        self.title = data ?? "空标题"   //设置标题
        self.collectionView?.backgroundColor = UIColor.white
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 每个Section的记录数量,同Android的getCount
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return resources!.count
    }
    
    // 记录个数, 注意indexPath是二维的; 类似于Android的getView
    // viewWithTag方法同Android的findViewById
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let identifier = "simpleCell"   //在StoryBoard文件里配置的
        
        //取出item布局
        let cell = (self.collectionView?.dequeueReusableCell(withReuseIdentifier: identifier,
                                                             for: indexPath))! as UICollectionViewCell
        let imageView = cell.contentView.viewWithTag(1) as! UIImageView  //在storyboard里设置UIImageView的tag为1
        let lable = cell.contentView.viewWithTag(2) as! UILabel  //在storyboard里设置tag为2
      
        imageView.image = UIImage(named: resources![indexPath.item]["pic"]!)
        lable.text = resources![indexPath.item]["name"]
        
        return cell     //同android的convertView
    }
    
    //点击事件
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("点击了 \(indexPath.item) ---- \(indexPath.section) --- \(indexPath.row)")
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("SimpleController prepare")
        
        //判断要打开的窗口, 虽然有父界面的对象,但不要在这个做父界面的逻辑。
        if let _ = segue.destination as? ViewController {
            print("准备打开的界面是父窗口")
        }
        
        //判断点击了哪个按钮
        if sender as? UIBarButtonItem == self.navigationItem.leftBarButtonItem {
            print("点击了左上角返回按钮")
            self.result = "列表窗口返回值"   //保存当前界面的数据
        }
    }
    

    }
    </pre>

    日志:
    prepare
    父界面传值: Optional("最简单CollectionView")
    SimpleController prepare
    准备打开的界面是父窗口
    点击了左上角返回按钮
    unwindToMain 子界面返回数据
    子界面返回值:Optional("列表窗口返回值"), 执行当前界面逻辑,如刷新界面等

    完整代码: http://download.csdn.net/detail/brycegao321/9792299

    相关文章

      网友评论

        本文标题:Swift实现最简单的UICollectionView

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