标签 ios控件 下的文章

团购页面模拟,swift版本

继续熟悉UITableView和之前的内容
这个只是模拟一下页面,页面整个就是一个UITableView,UITableView有一个自定义的头和尾,然后就是自定义的cell
需要注意的点:自定义xib,和xib的使用,自定义UITableViewCell,自定义代理协议,dispatch_after的使用

加载数据,注意kvc的读取的数据的键值要与对象的属性名称一致
//
//  Goods.swift
//  GroupBuying
//
//  Created by admin on 16/1/5.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class Goods: NSObject {
    var buyCount:NSString!
    var icon:NSString!
    var price:NSString!
    var title:NSString!
    //根据文件初始化对象数组
    class func instanceWithFile()->[Goods]
    {
        //读取plist文件内容
        let data = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("tgs", ofType: "plist")!)
        //循环初始化对象数组
        var goods:[Goods] = []
        for var i = 0;i < data?.count;i++
        {
            goods.append(self.instanceWithDic(data![i] as! [String : AnyObject]))
        }
        return goods
    }
    //根据字典初始化数组
    class func instanceWithDic(dic:[String : AnyObject])->Goods
    {
        let goods = Goods()
        //使用kvc赋值
        goods.setValuesForKeysWithDictionary(dic)
        return goods
    }
}
使用xib自定义cell,需要注意的是,要在xib的属性里面设置好 Identifier ,不然从缓冲池中取不到内容,依然会重复的创建与销毁对象
//
//  GoodsTableCell.swift
//  GroupBuying
//
//  Created by admin on 16/1/5.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//自定义 UITableViewCell 类
class GoodsTableCell: UITableViewCell {


    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var price: UILabel!
    @IBOutlet weak var buyCount: UILabel!
    @IBOutlet weak var icon: UIImageView!

    class func instanceWithTableView(tableView:UITableView,goods:Goods)->GoodsTableCell
    {
        //这个值要和在xib属性栏设置的 Identifier 一致
        let id = "goodsTableCell"
        //从缓存池中去内容,避免不必要的创建和销毁对象
        var temp:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(id)
        //因为可能缓存池是空的,取不出内容,所以这里做下处理
        if temp == nil
        {
            temp = NSBundle.mainBundle().loadNibNamed("GoodsTableCell", owner: nil, options: nil).last as! GoodsTableCell
        }
        //从缓存池取出的是 UITableViewCell 这里需要转换下,方便调用赋值方法
        let cell = temp as! GoodsTableCell
        //给子控件赋值
        cell.setData(goods)
        return cell
    }
    //设置子控件内容
    func setData(goods:Goods)
    {
        self.title.text = goods.title as String
        self.price.text = "¥\(goods.price as String)"
        self.buyCount.text = goods.buyCount as String + "人购买"
        self.icon.image = UIImage(imageLiteral: goods.icon as String)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
使用xib自定义footer,需要注意的是,dispatch_after的使用,和自定义协议
//
//  GoodsTableFooter.swift
//  GroupBuying
//
//  Created by admin on 16/1/5.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//定义代理协议
@objc protocol GoodsTableFooterLoadMoreDataButton:NSObjectProtocol
{
    optional func loadmoreDataButton()
}
class GoodsTableFooter: UIView {

    @IBOutlet weak var loadMoreButton: UIButton!
    @IBOutlet weak var loadMoreView: UIView!
    weak var delegate:GoodsTableFooterLoadMoreDataButton!
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    //当从nib文件中初始化称对象时会执行这个方法
    override func awakeFromNib() {
        super.awakeFromNib()
        //设置按钮圆角效果
        self.loadMoreButton.layer.cornerRadius = 5
        //设置按钮点击事件
        loadMoreButton.addTarget(self, action: "loadData:", forControlEvents: UIControlEvents.TouchDown)
    }
    //快速实例化对象
    class func instance()->GoodsTableFooter
    {
        let footer = NSBundle.mainBundle().loadNibNamed("GoodsTableFooter", owner: nil, options: nil).last as! GoodsTableFooter
        return footer
    }
    //
    func loadData(sender:UIButton)
    {
        //隐藏button按钮,显示菊花
        sender.hidden = true
        //这里设置下延时执行,之前没用过的一种方式,这个参数有一些特别,而且没有提示。。。。记录下
        let minseconds = 2 * Double(NSEC_PER_SEC)
        let dtime = dispatch_time(DISPATCH_TIME_NOW, Int64(minseconds))
        dispatch_after(dtime, dispatch_get_main_queue(), { () -> Void in
            let check = self.delegate?.respondsToSelector("loadmoreDataButton")
            //因为代理和代理和方法都是可选类型,所以这里需要做下判断是否执行代理方法
            if check != nil && (check!) == true
            {
                self.delegate.loadmoreDataButton!()
            }
            self.loadMoreButton.hidden = false

        })
    }
}
使用xib自定义header,需要注意的是,因为这个头里面包含一个图片轮播,所以需要用到定时器,scallView代理方法
//
//  GoodsTableHeader.swift
//  GroupBuying
//
//  Created by admin on 16/1/6.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class GoodsTableHeader: UIView,UIScrollViewDelegate {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    @IBOutlet weak var scallView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!
    //存放定时器,方便之后的停止
    var timer:NSTimer!
    //快速实例化的方法
    class func instance()->GoodsTableHeader
    {
        let header = NSBundle.mainBundle().loadNibNamed("GoodsTableHeader", owner: nil, options: nil).last as! GoodsTableHeader
        return header
    }
    //这个方法在xib从文件初始化成对象的时候调用
    override func awakeFromNib() {
        self.pageControl.numberOfPages = 5
        let w = self.scallView.frame.size.width
        let h = self.scallView.frame.size.height
        let y = self.scallView.frame.origin.y
        for var i = 0;i <= self.pageControl.numberOfPages;i++
        {
            let imageView:UIImageView = UIImageView()
            if i == self.pageControl.numberOfPages
            {
                imageView.image = UIImage(imageLiteral: "ad_" + String(format: "%02i", 0))
            }
            else
            {
                imageView.image = UIImage(imageLiteral: "ad_" + String(format: "%02i", i))
            }
            let x = CGFloat(i) * w
            imageView.frame = CGRectMake(x, y, w, h)
            self.scallView.addSubview(imageView)
        }
        self.scallView.contentSize = CGSizeMake(CGFloat(self.pageControl.numberOfPages) * w, h)
        self.scallView.pagingEnabled = true
        self.scallView.showsHorizontalScrollIndicator = false
        self.scallView.delegate = self
        self.startTimer()
    }
    //滚动过程设置 currentPage
    func scrollViewDidScroll(scrollView: UIScrollView) {
        var currentPage = Int((scallView.contentOffset.x + (0.5 * scallView.frame.size.width)) / scallView.frame.size.width)
        if currentPage > self.pageControl.numberOfPages - 1
        {
            currentPage = 0
        }
        self.pageControl.currentPage = currentPage
    }
    //手动拖动时,停止定时器
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.timer.invalidate()
    }
    //手动拖动完毕时,继续定时器
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.startTimer()
    }
    func startTimer()
    {
        //定时器
        self.timer = NSTimer(timeInterval: 2, target: self, selector: "changeImage", userInfo: nil, repeats: true)
        let runLoop = NSRunLoop.currentRunLoop()
        runLoop.addTimer(self.timer, forMode: NSRunLoopCommonModes)
    }
    //切换到下一张图片
    func changeImage()
    {
        var offect = CGPointMake(0, 0)

        if self.pageControl.currentPage == 0 && self.scallView.contentOffset.x > 0
        {
            self.scallView.contentOffset = offect
        }

        offect = CGPointMake(self.scallView.frame.size.width * CGFloat(self.pageControl.currentPage + 1), self.scallView.contentOffset.y)
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.scallView.contentOffset = offect
            })
    }
}
在控制器中调用,注意:完成了代理协议之后,要记得设置代理,刷新cell的方式

// // ViewController.swift // GroupBuying // // Created by admin on 16/1/5. // Copyright © 2016年 jin. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,GoodsTableFooterLoadMoreDataButton { @IBOutlet weak var tableView: UITableView! lazy var goods:[Goods] = Goods.instanceWithFile() override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self self.tableView.delegate = self //设置cell高度 self.tableView.rowHeight = 150 //设置tableFooter,注意,这里的Footer和代理方法中返回Footer的那个方法设置的Footer可不一样 let footer = GoodsTableFooter.instance() footer.delegate = self self.tableView.tableFooterView = footer //设置header self.tableView.tableHeaderView = GoodsTableHeader.instance() // 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. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.goods.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = GoodsTableCell.instanceWithTableView(self.tableView, goods: self.goods[indexPath.row]) return cell } // func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { // var footer:GoodsTableFooter = NSBundle.mainBundle().loadNibNamed("GoodsTableFooter", owner: nil, options: nil).last as! GoodsTableFooter // return footer // } // func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // return 80 // } //代理Footer的加载更多数据的方法 func loadmoreDataButton() { let goods = Goods() goods.title = "鱼香肉丝" goods.price = "10" goods.buyCount = "30" goods.icon = "37e4761e6ecf56a2d78685df7157f097.png" //添加数据到cell数据的来源数组 self.goods.append(goods) //刷新cell,但是这个方法是刷新所有的cell,其实这里只添加了1个数据而已,虽然能达到效果,但是这个不好 // self.tableView.reloadData() //这个是重新刷新指定的cell,也就是说需要这个行之前就存在,这里加的行在之前是不存在的,所以会报错 // self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: self.goods.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade) //这个方法是插入一行,这里用这个最好 self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.goods.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade) } }

图片轮播swift版本

有几个需要注意的地方,scallView的常用属性,代理的使用,定时器的使用,定时器不同模式的区别,UIPageControl的使用

//
//  ViewController.swift
//  图片轮播
//
//  Created by admin on 15/12/31.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit
//遵循了UIScrollViewDelegate协议,作为scallView的代理
class ViewController: UIViewController,UIScrollViewDelegate{

    @IBOutlet weak var scallView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!
    var timer:NSTimer!
    override func viewDidLoad() {
        super.viewDidLoad()

        let w = scallView.frame.size.width
        let h = scallView.frame.size.height
        let colnum = 5
        for var i = 1;i <= colnum + 1;i++
        {
            var imageView:UIImageView = UIImageView()
            //多添加一个图片,让轮播效果更顺眼
            if i > colnum
            {
                imageView.image = UIImage(imageLiteral: "img_01")
            }
            else
            {
                imageView.image = UIImage(imageLiteral: "img_" + String(format: "%02i", i))
            }
            let x = CGFloat(i - 1) * w
            imageView.frame = CGRectMake(x, 0, w, h)
            scallView.addSubview(imageView)
        }

        //scallView可拖动区域的大小
        scallView.contentSize = CGSizeMake(CGFloat(colnum) * w, 0)
        scallView.showsHorizontalScrollIndicator = false//去掉横向滚动条
        scallView.pagingEnabled = true//打开分页
        //设置UIPageControl的点的个数
        pageControl.numberOfPages = column
        //设置scallView的代理
        scallView.delegate = self
        //设置活动分页的颜色
        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
        //设置活动分页之外分页的颜色
        pageControl.pageIndicatorTintColor = UIColor.blackColor()
        //添加定时器,自动切换图片
        self.addTimer()

    }
    //图片切换
    func imageChange()
    {
        var coordinates:CGPoint = CGPoint(x: 0,y: 0)
        //为了从最后一张切换到第一张的时候不那么突兀,这里需要处理
        if pageControl.currentPage == 0 && scallView.contentOffset.x > 0
        {
            coordinates = CGPoint(x: 0, y: scallView.contentOffset.y)
            self.scallView.contentOffset = coordinates
        }
        coordinates = CGPoint(x: CGFloat(pageControl.currentPage + 1) * scallView.frame.size.width, y: scallView.contentOffset.y)
        //动画效果
        UIView.animateWithDuration(1, animations: {
            self.scallView.contentOffset = coordinates
        })
    }
    //添加定时器的方法
    func addTimer()
    {
        //初始化定时器
        self.timer = NSTimer(timeInterval: 3, target: self, selector: "imageChange", userInfo: nil, repeats: true)
        //获得当前消息循环
        var runLoop = NSRunLoop.currentRunLoop()
        //把定时器以默认模式添加进当前消息循环,分为两种模式
//        runLoop.addTimer(self.timer, forMode: NSDefaultRunLoopMode)
        runLoop.addTimer(self.timer, forMode: NSRunLoopCommonModes)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //scrollView代理方法,滚动时
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //获得当前页数
        let currentPage = Int((scallView.contentOffset.x + (scallView.frame.size.width * 0.5)) / scallView.frame.size.width)
        //因为多加了一个图片,所以这里需要处理下
        if currentPage >= pageControl.numberOfPages
        {
            pageControl.currentPage = 0
        }
        else
        {
            pageControl.currentPage = currentPage
        }
    }
    //scallView代理方法,开始拖拽
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.timer.invalidate()
    }
    //scallView代理方法,结束拖拽
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //创建定时器并加入当前消息循环,默认模式
//        self.timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "imageChange", userInfo: nil, repeats: true)
        self.addTimer()
    }

}

超级猜图swift

代码太多,贴几个重点吧

通过plist初始化(kvc),可以很方便的对类的属性进行赋值
//
//  Question.swift
//  超级猜图
//
//  Created by admin on 15/12/30.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class Question: NSObject {
    var answer:NSString!
    var icon:NSString!
    var title:NSString!
    var options:NSArray!
    //加载文件,初始化对象数组
    class func loadQuestionOfFile()->[Question]
    {
        let datas:NSArray! = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("questions", ofType: "plist")!)
        var temp:[Question] = []
        for data in datas
        {
            temp.append(Question.instance(data as! NSDictionary))
        }
        return temp
    }
    //传入字典,初始化对象
    class func instance(questionData:NSDictionary)->Question
    {
//        var temp = Question(answer:questionData["answer"] as! NSString,title:questionData["title"] as! NSString,icon:questionData["icon"] as! NSString,option:questionData["option"] as! NSArray)
//        self.init(answer:questionData["answer"] as! NSString,title:questionData["title"] as! NSString,icon:questionData["icon"] as! NSString,option:questionData["options"] as! NSArray)
        let temp = Question()
        //直接使用字典的键值对队完成对对象属性的肤赋值
        temp.setValuesForKeysWithDictionary(questionData as! [String : AnyObject])
        return temp
    }
}

kvc其它用法
//取出对象数组中对象的icon值
print((self.questions as NSArray).valueForKeyPath("icon")!)
//取出对象数组中对象的book值(是一个类)的name属性,这里执行会报错,oc使用点分割swift呢?
print(self.questions[0].valueForKeyPath("book.name"))
隐藏程序界面状态栏
override func prefersStatusBarHidden() -> Bool {
     return true
}
隐藏启动界面状态栏

General>Deployment Info>Hide status bar勾选就好了

修改状态栏 style
override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent//居中
}
删除子控件
self.answerButtonView.subviews.forEach({$0.removeFromSuperview()})
弹出框
var alert = UIAlertView(title: "提示", message: "后面没有题了", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确认", "测试A","测试B")
控件放到最顶层
self.view.bringSubviewToFront(self.imageView)

九宫格的修改

之前的九宫格的控件都是用代码加的,这里改用xib,http://jinblog.com/archives/285.html

1.新建xib,这个直接在在项目里面新建一个User Interface->Empty就好了
2.拖控件
3.设置好xib的Custom Class
4.设置好控件和Custom Class类的关联,Custom Class代码如下

//
//  AppBlockView.swift
//  九宫格
//
//  Created by admin on 15/12/28.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class AppBlockView: UIView {


    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var lable: UILabel!
    //类方法,用来方便的实例话xib
    class func instance()->UIView
    {
        //加载xib的方法
        return NSBundle.mainBundle().loadNibNamed("AppBlockView", owner: nil, options: nil).last as! AppBlockView
    }
}

4.使用,这里碰到一个问题,xib里面的imageview没有办法去修改大小,修改成功了,但是运行效果确还是那么大的

//加载xib
var blockView = AppBlockView.instance() as! AppBlockView
//xib里面有个 imageview ,设置下图片
blockView.imageView.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("icon_00", ofType: "png")!)!
//输出宽肚,输出结果是: 214.0
print(blockView.imageView.frame.width)
//设置 fram
blockView.imageView.frame = CGRectMake(100,100, 10, 10)
blockView.imageView.backgroundColor = UIColor.blackColor()
//输出宽 输出结果是  10.0,设置输出的结果就是修改之后的结果,但是运行的话,看上去还是那么大
print(blockView.imageView.frame.width)
blockView.button.addTarget(self, action: "showInfo:", forControlEvents: UIControlEvents.TouchDown)

动画函数的用法

UIView.animateWithDuration(3, animations: {
    self.lable.alpha = 0
}, completion:
{
     (status) in
     //设置当前按钮的图片和文字,禁用点击
     button.setBackgroundImage(UIImage(imageLiteral: "buttongreen"), forState: UIControlState.Normal)
     button.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Highlighted)
     button.setTitle("下载完成", forState: UIControlState.Normal)
     button.enabled = false
     //设置lable透明度
     self.lable.alpha = 1
     //移除lable
     self.lable.removeFromSuperview()
     //允许用户和页面交互,这个值在点击事件发生之后会被设置成`false`,用户就不能点击界面的任何按钮了,所以这里需要复原
     self.view.userInteractionEnabled = true
})

九宫格

//
//  ViewController.swift
//  九宫格
//
//  Created by admin on 15/12/26.
//  Copyright © 2015年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    //存放通知消息的lable
    lazy var lable:UILabel =
    {
        var lable = UILabel()
        //设置宽度
        lable.frame.size.width = 100
        //设置高度
        lable.frame.size.height = 20
        //设置位置
        lable.transform = CGAffineTransformMakeTranslation(UIScreen.mainScreen().bounds.size.width/2 - lable.frame.size.width/2, UIScreen.mainScreen().bounds.size.height/2)
        //设置背景颜色
        lable.backgroundColor = UIColor(red: 0.483992,green:0.638788,blue: 1, alpha: 1)
        //设置文字
        lable.text = "正在下载中........"
        //设置圆角,button可以设置,lable没有效果啊
        lable.layer.cornerRadius = 50
        return lable
    }()
    //当前最后一个插入主视图在数组中的下标
    var dataIndex:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        //获得图片信息
        let data = NSArray.init(contentsOfFile: NSBundle.mainBundle().pathForResource("app", ofType: "plist")!)
        //循环添加控件
        for (var (index,blockInfo)) in EnumerateSequence(data!)
        {
            //获得图片
            let image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource(String(blockInfo["icon"]!!), ofType: "png")!)
            //获得图片描述
            let descreption = String(blockInfo["name"]!!)
            //设置最后插入视图的数据的在数据数组中的下标
            self.dataIndex = index
            //执行插入
            addChildBlok(image!,description: descreption,dataIndex: self.dataIndex)
        }
    }
    //UIImage好像没有直接缩放的办法,就用这个完成缩放
    func scalImage(image:UIImage,scal:CGFloat)->UIImage
    {
        //创建 CGSize 对象记录下缩放改变比例之后的宽高,方便之后的使用
        let imageSize = CGSize(width: CGFloat(image.size.width*scal),height: CGFloat(image.size.height*scal))
        //创建一个 bitmap 大小的 context
        UIGraphicsBeginImageContext(imageSize)
        //绘制改变大小的图片
        image.drawInRect(CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
        //从当前context中创建一个改变大小后的图片
        let imageTest = UIGraphicsGetImageFromCurrentImageContext()
        //使当前 context 出栈
        UIGraphicsEndImageContext()
        return imageTest
    }
    func addChildBlok(image:UIImage,description:String,dataIndex:Int)
    {
        //列数是计算而成的,初始化是散列
        var column = 3
        //这里可以通过屏幕的宽度来选择显示多少条
        if UIScreen.mainScreen().bounds.size.width > 0
        {
            column = 4
        }

        //获得屏幕当前 view 的左边距
        var marginLeft = Int(UIScreen.mainScreen().bounds.size.width * 0.05)
        //上边距
        let marginTop = 20
        //获得 view 的宽度
        let blockViewWidth = Int(UIScreen.mainScreen().bounds.size.width * 0.8 / CGFloat(column))
        //重新设置左边距,以达到居中的效果
        marginLeft = (Int(UIScreen.mainScreen().bounds.size.width) - column * blockViewWidth) / 2


        //创建 view


        let blockView = UIView(frame: CGRect(x: 0,y: 0,width: 0,height: 0))

        //设置blockview颜色,用以调试
        //blockView.backgroundColor = UIColor(red:0.483992,green:0.638788,blue: 1,alpha: 1)
        self.view.addSubview(blockView)

        //获得图片信息
        var image = image
        let descreption = description
        //缩放图片
        image = scalImage(image, scal: (CGFloat(blockViewWidth) * 0.8)/image.size.width)

        //创建 UIImageView 承载图片
        let imageView = UIImageView(image: image)
        //改变UIImageView位置
        let imageMarginLeft = CGFloat((Double(blockViewWidth) * 0.1))
        let imageMarginTop = CGFloat((Double(blockViewWidth) * 0.1))
        imageView.transform = CGAffineTransformTranslate(imageView.transform, imageMarginLeft, imageMarginTop)

        //加入当前view中
        blockView.addSubview(imageView)


        //加入 UIlable ,并设定好坐标和大小
        let lableMarginLeft = imageMarginLeft
        let lableMarginTop = imageMarginTop + imageView.frame.height
        let lable = UILabel(frame: CGRect(x: lableMarginLeft,y: lableMarginTop,width: CGFloat((Double(blockViewWidth) * 0.8)),height: 10))
        //像这样直接创建一个,设置字体没有效果
        //lable.font = UIFont(name: "System", size: CGFloat(10))
        //改变字体的大小
        lable.font = lable.font.fontWithSize(8)
        //改变字体对齐方式
        lable.textAlignment = NSTextAlignment.Center
        //设置lable显示的文字
        lable.text = descreption
        blockView.addSubview(lable)

        //加入button并设定好位置信息
        let buttonMarginLeft = imageMarginLeft
        let buttonMarginTop = imageMarginTop + lable.frame.height + imageView.frame.height
        let button = UIButton(frame: CGRect(x: buttonMarginLeft,y: buttonMarginTop,width: CGFloat((Double(blockViewWidth) * 0.8)),height: 10))
        //设置背景图片
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Highlighted)
        //设置title
        button.setTitle("点击下载", forState: UIControlState.Normal)
        button.setTitle("正在下载", forState: UIControlState.Highlighted)
        //设置字体大小
        button.titleLabel?.font = button.titleLabel?.font.fontWithSize(7)
        //绑定事件
        button.addTarget(self, action: "showInfo:", forControlEvents: UIControlEvents.TouchDown)
        //设定当前view的坐标和大小
        let blockViewHeight = imageMarginTop + imageView.frame.height + lable.frame.height + button.frame.height
        let blockViewX = (dataIndex%column) * blockViewWidth + marginLeft
        let blovkViewY = (dataIndex/column) * Int(blockViewHeight) + marginTop
        blockView.frame = CGRectMake(CGFloat(blockViewX), CGFloat(blovkViewY), CGFloat(blockViewWidth), CGFloat(blockViewHeight))

        blockView.addSubview(button)

//        self.view.bringSubviewToFront(button)
        //出现一次情况,按钮点击之后没有任何反应,搞了半天,后来想到用这个办法调试,发现原来是button的位置不在父控件的view之内
//        blockView.backgroundColor = UIColor(red:0.483992,green:0.638788,blue: 1,alpha: 1)
//        imageView.backgroundColor = UIColor(red:0.12323,green:0.123123,blue: 1,alpha: 1)


    }
    //按钮点击事件,显示一个lable
    func showInfo(sender:UIButton)
    {
        //改变当前点击按钮的图片和文字,禁用点击
        sender.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Normal)
        sender.setTitle("正在下载", forState: UIControlState.Normal)
        sender.enabled = false
        //显示lable按钮
        self.view.addSubview(self.lable)
        //延时执行函数
        self.performSelector("hideInfo:", withObject: sender, afterDelay: 1)
    }
    //执行完毕,隐藏lable
    func hideInfo(button:AnyObject)
    {
        //设置lable透明度
        UIView.animateWithDuration(3, animations: {
            self.lable.alpha = 0
        })
        //延时执行函数,初始化执行完毕的信息
        self.performSelector("endDownload:", withObject: button, afterDelay: 3)
    }
    //进行下载完成之后的初始化
    func endDownload(button:UIButton)
    {
        //设置当前按钮的图片和文字,禁用点击
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(imageLiteral: "buttongreen_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("下载完成", forState: UIControlState.Normal)
        button.enabled = false
        //设置lable透明度
        self.lable.alpha = 1
        //移除lable
        self.lable.removeFromSuperview()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}