swift中collectionView的简单用法

之前写过OC中collectionView的用法,现在再看看swift中collectionView的用法,有兴趣的朋友,可以两者前后比较下区别,swift现在没有稳定下来,语法更新的比较快,但是它核心的一些东西,已经定型了。这些还是靠读者们自己去挖掘吧。

//这里签署数据源和代理,此时不需要引入layout的代理,也可以。class AmonViewController: UIViewController ,UICollectionViewDataSource,UICollectionViewDelegate{

    var _collectionView:UICollectionView?;
    var _dataArray:NSArray?;

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);

        self.tabBarController?.tabBar.hidden = false;

//        let x = self._collectionView!.contentOffset.x/kScreenW;
//        UIView.animateWithDuration(0.25) { () -> Void in
//
//            self._collectionView?.contentOffset = CGPointMake(kScreenW * CGFloat(Int64(x)) + 10 * CGFloat(Int64(x)), 0);
//        };
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "排行";//此属性设置为false可以解决由于scrollview引起的界面bug
        self.automaticallyAdjustsScrollViewInsets = false;
        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor();
        let headerView = AmonCirHeadView(frame: CGRectMake(0, 64, kScreenW, 150));
        self.view.addSubview(headerView);

     //创建layout
        let layOut = UICollectionViewFlowLayout();
    //设置滚动方向
//        layOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layOut.scrollDirection = UICollectionViewScrollDirection.Horizontal;
        layOut.itemSize = CGSizeMake(kScreenW, kScreenH-headerView.bounds.size.height-49-64);
        //垂直方向间距
        layOut.minimumInteritemSpacing = 0;
        //水平方向间距
        layOut.minimumLineSpacing = 0;
        //设置四周得边缘距离
        layOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _collectionView = UICollectionView(frame: CGRectMake(0, headerView.bottom, kScreenW, kScreenH-headerView.bounds.size.height-49-64), collectionViewLayout: layOut);
        self.view.addSubview(_collectionView!);

        _collectionView?.delegate = self;
        _collectionView?.dataSource = self;//是否分页
        _collectionView?.pagingEnabled = true;
        _collectionView?.backgroundColor = UIColor.whiteColor();
    _collectionView?.registerClass(UICollectionViewCell().classForCoder, forCellWithReuseIdentifier: "item");

        loadData();
    }

    //data Source
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1;
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self._dataArray==nil{

            return 0;
        }
        return (self._dataArray?.count)!;
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("item", forIndexPath: indexPath);

        var imgV = cell.contentView.viewWithTag(2016052519) as? UIImageView;
        var lab = cell.contentView.viewWithTag(2016052520) as? UILabel;
        if imgV == nil{
            imgV = UIImageView(frame: cell.bounds);
            cell.contentView.addSubview(imgV!);
            imgV?.tag = 2016052519;
            imgV!.image = UIImage(named: "AION-天气背景.jpg");
            lab = UILabel();
            lab?.frame = CGRectMake(0, 0, kScreenW, 30);
            lab!.tag = 2016052520;

            lab?.textAlignment = NSTextAlignment.Center;
            lab?.textColor = UIColor.whiteColor();
            lab?.backgroundColor = UIColor.blackColor();
            lab?.alpha = 0.3;
            cell.contentView.addSubview(lab!);
            lab?.numberOfLines = 0;
            lab?.font = UIFont.systemFontOfSize(12);
            lab?.text = "最好看的小说,尽在BQPReader";
        }//数据解析
        let dic1 = self._dataArray![indexPath.item] as! NSDictionary;
        let dic = dic1.objectForKey("content") as! NSDictionary;
        let title = dic.objectForKey("title") as! String;
        let desc = dic.objectForKey("desc") as! String;
        lab?.text = title + "\n" + desc;

        return cell;
    }

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
//        let x = scrollView.contentOffset.x/kScreenW;
//        UIView.animateWithDuration(0.25) { () -> Void in

//        self._collectionView?.contentOffset = CGPointMake(kScreenW * CGFloat(Int64(x)) + 10 * CGFloat(Int64(x)), 0);
//        };

    }
    //delegate
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let viewC = SecAmonViewController();
        let dic1 = self._dataArray![indexPath.item] as! NSDictionary;
        let dic = dic1.objectForKey("content") as! NSDictionary;
        viewC.title = dic.objectForKey("title") as? String;
        self.navigationController?.pushViewController(viewC, animated: true);
    }
    //自定义的数据请求方法
    func loadData(){
        CoreWork.homeOneSecondThirdList { (responsObject) -> Void in

            let firDic = responsObject;
            if firDic.isKindOfClass(NSDictionary) == false{
                return;
            }
            let secondDic = firDic.objectForKey("data") as! NSDictionary;
            self._dataArray = secondDic.objectForKey("md")?.objectForKey("module") as? NSArray;

            self._collectionView?.reloadData();
        }

    }

}
时间: 2024-08-26 00:58:47

swift中collectionView的简单用法的相关文章

java中Object.equals()简单用法

/* equals()方法默认的比较两个对象的引用! */ class Child { int num; public Child(int x){ num = x; } //人文的抛出运行时异常的好处是:可以自定义错误信息! /*public boolean equals(Object o) throws ClassCastException{ if(!(o instanceof Child)) throw new ClassCastException("中文提示:类型错误"); Ch

Android中AsyncTask的简单用法【转】

在开发Android移动客户端的时候往往要使用多线程来进行操作,我们通常会将耗时的操作放在单独的线程执行,避免其占用主线程而给用户带来不好的用户体验.但是在子线程中无法去操作主线程(UI 线程),在子线程中操作UI线程会出现错误.因此android提供了一个类Handler来在子线程中来更新UI线程,用发消息的机制更新UI界面,呈现给用户.这样就解决了子线程更新UI的问题.但是费时的任务操作总会启动一些匿名的子线程,太多的子线程给系统带来巨大的负担,随之带来一些性能问题.因此android提供了

Swift中协议的简单介绍

熟悉objective-c语言的同学们肯定对协议都不陌生,在Swift中苹果将 protocol 这种语法发扬的更加深入和彻底.Swift语言中的 protocol 不仅能定义方法还能定义属性,配合 extension 扩展的使用还能提供一些方法的默认实现,而且不仅类可以遵循协议,现在的枚举和结构体也能遵循协议了.基于此本文从 1,协议中定义属性和方法 , 2,协议的继承.聚合.关联类型 , 3,协议的扩展 , 4,Swift标准库中常见的协议 , 5,为什么要使用协议 5个方面结合自身的学习经

C# Winfom 中ListBox的简单用法

Winform控件ListBox的用法 1.如何添加listBox的值 this.listBox1.Items.Add("张晓东"); 2.如何判断listBox集合是否添加过 //检查添加值是否添加过 if(this.listBox1.items.Contains("张晓东")){ MessageBox.show("集合成员已添加过!"); } else{ //执行添加集合成员 } 3.如何获取listBox选中的值 //判断所有选中项集合大于

(数据科学学习手札54)Python中retry的简单用法

一.简介 retry是一个用于错误处理的模块,功能类似try-except,但更加快捷方便,本文就将简单地介绍一下retry的基本用法. 二.基本用法 retry: 作为装饰器进行使用,不传入参数时功能如下例所示: from retry import retry @retry() def demo(): print('错误') raise demo() 我们编写了每次运行都会通过raise报错的自定义函数demo(),利用默认参数的retry()进行装饰,运行结果如下: 可以看到,retry()

C++中template的简单用法

模板(Template)指C++程序设计设计语言中采用类型作为参数的程序设计,支持通用程序设计.C++ 的标准库提供许多有用的函数大多结合了模板的观念,如STL以及IO Stream.使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数.返回值取得任意类型. 一.函数模板 在c++入门中,很多人会接触swap(int&, int&)这样的函数类似代码如下: 1 void swap(int&a , int& b) { 2 int temp

easyui中parser的简单用法

在easyUI中,parser是在页面加载完成之后自动加载,将代码根据class渲染为不同的插件.除了自动加载之后,编程人员还可以使用手动调用的方式,比如$.parser.parse("#id")的方式进行调用,这样就可以允许编程人员根据不同需求动态加入不同的插件的代码,再使用该段代码的唯一id,利用parser进行渲染,比如插入插件代码至页面,代码如下: <div class="easyui-accordion" id="tt">

C#Winform中ToolTip的简单用法,

ToolTip它能够为我们的软件提供非常漂亮的提示信息,提高软件的可用性,给用户比较好的体验. 使用,在窗体加载时加载以下代码: var toolTip1 = new ToolTip(); toolTip1.AutoPopDelay = 10000; toolTip1.InitialDelay = 500; toolTip1.ReshowDelay = 500; toolTip1.ShowAlways = true; toolTip1.SetToolTip(this.label26, @"系统所

java中swing的简单用法,做一个小界面

package zzn; import javax.swing.*; public class demoui extends JFrame { public static void main(String[] args) { demoui ui=new demoui(); } public demoui() { this.setVisible(true); this.setSize(500,500); } }