标签:
class NetworkTools: AFHTTPSessionManager {
//1.将NetworkTools设置成单例
static let shareIntance : NetworkTools = {
let tools = NetworkTools()
//加上这句能增加解析的种类
tools.responseSerializer.acceptableContentTypes?.insert("text/html")
return tools
}()
}
// Mark: - 定义枚举,用来作为传值的参数
enum RequestType {
case GET
case POST
}
// MARK: - 封装网络请求
extension NetworkTools {
//注意需要传入的参数:请求的方式;url;需要拼接的参数;成功后的回调(闭包)
func request(requestType: RequestType, urlString: String, parameters: [String : AnyObject], finished: (result : AnyObject?, error : NSError?) ->()) {
//定义成功后的闭包
let successCallBack = {(task : NSURLSessionDataTask, result : AnyObject?) -> Void in finished(result: result, error: nil)
}
//定义失败后的闭包
let failureCallBack = {(task : NSURLSessionDataTask?, error : NSError) -> Void in finished(result: nil, error: error)
}
//根据传入的参数判断选择哪种请求方式
if requestType == .GET {
GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}else{
POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}
}
}
//请求首页数据
extension NetworkTools {
//需要有回调后的参数(闭包)
func loadHomeData (offSet : Int, finished : (result : [[String : AnyObject]]?, error : NSError?) -> ()) {
//1. 获取url
let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
//2. 拼接请求参数
let parameters = [
"offset" : "\(offSet)",
"limit" : "30",
"access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"
]
//3. 发送请求
request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
// 3.1 判断请求是否出错
if error != nil {
finished(result: nil, error: error)
}
//3.2 获取结果(将可选类型的结果转为具体的结果)
guard let result = result as? [String : AnyObject] else {
finished(result: nil, error: NSError(domain: "data error", code: -1011, userInfo: nil))
return
}
//3.3 将结果回调
finished(result: result["data"] as? [[String : AnyObject]], error: nil)
}
}
}
class ShopItem: NSObject {
//模型中需要用到的属性
var q_pic_url = ""
var z_pic_url = ""
//字典转模型
init(dict : [String : AnyObject]) {
super.init()
//KVC
setValuesForKeysWithDictionary(dict)
}
//重写系统由于模型中属性不是一一对应会报错的函数(重写函数中什么都不做,就不会报错)
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
//MARK: - 给类扩充方法
extension HomeViewController {
//cell的个数
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//根据模型中的数据才能知道有多少个cell
return self.shops.count
}
//cell的内容
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//注册
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeCell", forIndexPath: indexPath) as! HomeViewCell
//取出item
cell.shops = shops[indexPath.item]
//判断是否是最后一个出现(如果是最后一个,那么久再次请求数据)
if indexPath.item == self.shops.count - 1 {
loadData(self.shops.count)
}
return cell
}
//点击cell[弹出控制器
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
showPhotoBrowser(indexPath)
}
}
class HomeCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
//列数
let cols : CGFloat = 3
//间距
let margin : CGFloat = 10
//宽度和高度
let itemWH = (UIScreen.mainScreen().bounds.width - (cols + 1) * margin) / cols
//设置布局内容
itemSize = CGSize(width: itemWH, height: itemWH)
minimumInteritemSpacing = margin
minimumLineSpacing = margin
//设置内边距
collectionView?.contentInset = UIEdgeInsets(top: margin + 64, left: margin, bottom: margin, right: margin)
}
}
import UIKit
import SDWebImage
class HomeViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
//didSet方法
var shops : ShopItem? {
didSet {
//1. 校验
guard let urlString = shops?.z_pic_url else {
return
}
//2.创建url
let url = NSURL(string: urlString)
//3.设置图片
imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "empty_picture"))
}
}
}
class HomeViewController: UICollectionViewController {
//懒加载装模型的数组
private lazy var shops : [ShopItem] = [ShopItem]()
private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
override func viewDidLoad() {
super.viewDidLoad()
//调用网络请求函数
loadData(0)
}
}
//MARK: - 发送网络请求
extension HomeViewController {
//加载数据
func loadData(offSet : Int) {
NetworkTools.shareIntance.loadHomeData(offSet) { (result, error) -> () in
//1. 错误校验
if error != nil {
//打印错误信息
print(error)
return
}
//2. 获取结果
guard let resultArray = result else {
print("获取的结果不正确")
return
}
//3. 遍历所有的结果
for resultDict in resultArray {
// print(resultDict)
let shop : ShopItem = ShopItem(dict : resultDict)
self.shops.append(shop)
}
//4.刷新表格
self.collectionView?.reloadData()
}
}
}
//点击cell弹出控制器
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
showPhotoBrowser(indexPath)
}
//Mark: - 点击图片,弹出控制器
extension HomeViewController {
//定义为私有的
private func showPhotoBrowser( indexPath : NSIndexPath) {
//创建控制器对象
let showPhotoBrowserVC = PhotoBrowserController()
//传入点击的cell的角标
showPhotoBrowserVC.indexPath = indexPath
//让model出来的控制器和源控制器中模型数据相等
showPhotoBrowserVC.shopItem = shops
showPhotoBrowserVC.view.backgroundColor = UIColor.redColor()
//设置model出控制器的模式
showPhotoBrowserVC.modalPresentationStyle = .Custom
// showPhotoBrowserVC.modalTransitionStyle = .PartialCurl
//设置动画代理
showPhotoBrowserVC.transitioningDelegate = photoBrowserAnimator
//model出控制器
presentViewController(showPhotoBrowserVC, animated: true, completion: nil)
}
}
//创建类
extension UIButton {
//便利构造函数
//函数前面必须加上convenience关键字
convenience init(title : String, bgColor : UIColor, fontSize : CGFloat) {
self.init()
backgroundColor = bgColor
setTitle(title, forState: .Normal)
titleLabel?.font = UIFont.systemFontOfSize(fontSize)
}
}
class PhotoBrowserController: UIViewController {
//定义属性
let PhoptoBrowserCell = "PhoptoBrowserCell"
var shopItem : [ShopItem]?
var indexPath : NSIndexPath?
//1.懒加载(model出来的控制器;保存按钮;取消按钮)
lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), collectionViewLayout: PhotoBrowerFlowLayout())
lazy var colseBtn : UIButton = UIButton(title: "关 闭", bgColor:UIColor.darkGrayColor() , fontSize: 16.0)
lazy var saveBtn : UIButton = UIButton(title: "保 存", bgColor: UIColor.darkGrayColor(), fontSize: 16.0)
override func viewDidLoad() {
super.viewDidLoad()
//添加UI控件
setUpUI()
//滚到对应的位置
collectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: .Left, animated: false)
}
//Mark: - 添加UI控件
extension PhotoBrowserController {
func setUpUI() {
//1. 添加控件到view中
view.addSubview(collectionView)
view.addSubview(colseBtn)
view.addSubview(saveBtn)
//2. 设置子控件的frame
//2.1 设置collectionView
collectionView.frame = view.bounds
//2.2 设置关闭按钮
let colseBtnX : CGFloat = 20.0
let colseBtnW : CGFloat = 90.0
let colseBtnH : CGFloat = 32.0
let colseBtnY : CGFloat = view.bounds.height - colseBtnH - 20.0
colseBtn.frame = CGRectMake(colseBtnX, colseBtnY, colseBtnW, colseBtnH)
//2.3 设置保存按钮
let saveBtnX = view.bounds.width - colseBtnW - 20
saveBtn.frame = CGRectMake(saveBtnX, colseBtnY, colseBtnW, colseBtnH)
//监听按钮的点击
colseBtn.addTarget(self, action: "closeBtnClick", forControlEvents: .TouchUpInside)
saveBtn.addTarget(self, action: "saveBtnClick", forControlEvents: .TouchUpInside)
//注册
collectionView.registerClass(PhotoBrowerViewCell.self, forCellWithReuseIdentifier: PhoptoBrowserCell)
//设置数据源
collectionView.dataSource = self
//设置代理
collectionView.delegate = self
}
}
extension PhotoBrowserController : UICollectionViewDataSource,UICollectionViewDelegate {
//MARK: - cell的个数
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return shopItem?.count ?? 0
}
//MARK: - cell的内容
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhoptoBrowserCell, forIndexPath: indexPath) as! PhotoBrowerViewCell
cell.shopItem = shopItem?[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//调用closeBtnClick方法
closeBtnClick()
}
}
extension PhotoBrowserController {
@objc private func closeBtnClick () {
// print("closeBtnClick")
//dismiss控制器
dismissViewControllerAnimated(true, completion: nil)
}
@objc private func saveBtnClick() {
// print("saveBtnClick")
//取出在屏幕中显示的cell
let cell = collectionView.visibleCells().first as! PhotoBrowerViewCell
//取出图片(该方法中的imageView不能直接拿来用,因为设置了为私有的)
let image = cell.imageView.image
//保存图片到相册
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}
}
class PhotoBrowerFlowLayout: UICollectionViewFlowLayout {
//设置流水布局相关属性
override func prepareLayout() {
super.prepareLayout()
itemSize = (collectionView?.bounds.size)!
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = .Horizontal
//设置分页
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
}
}
class PhotoBrowerViewCell: UICollectionViewCell {
//懒加载显示图片的控件
lazy var imageView : UIImageView = UIImageView()
//提供加载图片的模型的set方法
var shopItem : ShopItem? {
didSet {
//1.校验小图片的url是否为空
guard let urlString = shopItem?.q_pic_url else {
return
}
//2. 去Cach中获取小图
var smallImage = SDWebImageManager.sharedManager().imageCache.imageFromMemoryCacheForKey(urlString)
//3.如果获取不到图片就赋值为占位图片
if smallImage == nil {
smallImage = UIImage(named: "empty_picture")
}
//4. 计算展示的图片的frame
imageView.frame = calculate(smallImage)
//5. 获取大图片的url是否为空
guard let bigUrlString = shopItem?.z_pic_url else {
return
}
//6 .创建大图的url
let bigUrl = NSURL(string: bigUrlString)
//7. 加载大图
imageView.sd_setImageWithURL(bigUrl, placeholderImage: smallImage, options: .RetryFailed) {(image, error, type, url) -> Void in
self.imageView.frame = self.calculate(image)
}
}
}
// MARK: - 构造函数
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 构造函数
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 设置图片的frame
extension PhotoBrowerViewCell {
private func calculate (image : UIImage) ->CGRect {
let imageViewX : CGFloat = 0.0
let imageViewW : CGFloat = UIScreen.mainScreen().bounds.width
let imageViewH : CGFloat = imageViewW / image.size.width * image.size.height
let imageViewY : CGFloat = (UIScreen.mainScreen().bounds.height - imageViewH) * 0.5
return CGRect(x: imageViewX, y: imageViewY, width: imageViewW, height: imageViewH)
}
}
//MARK: - 添加子控件
extension PhotoBrowerViewCell {
private func setUpUI() {
contentView.addSubview(imageView)
}
}
showPhotoBrowserVC.modalTransitionStyle = .PartialCurl
showPhotoBrowserVC.transitioningDelegate = photoBrowserAnimator
class PhotoBrowserAnimator: NSObject {
var isPresented : Bool = false
}
//MARK: - 实现转场动画的代理方法
extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate {
//弹出动画交给谁管理
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
//消失动画交给谁管理
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
}
extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning {
//返回动画执行的时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 2.0
}
//获取转场的上下文:可以通过上下文获取到执行动画的view
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
isPresented ? animateForPresentView(transitionContext) : animateForDismissed(transitionContext)
}
//弹出
func animateForPresentView(transitionContext: UIViewControllerContextTransitioning) {
//1 取出弹出的view
let presentView = transitionContext.viewForKey(UITransitionContextToViewKey)!
//2 将弹出的view加入到contentView中
transitionContext.containerView()?.addSubview(presentView)
//3 执行动画
presentView.alpha = 0.0
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
presentView.alpha = 1.0
}) { (_) -> Void in
//完成动画
transitionContext.completeTransition(true)
}
}
//消失
func animateForDismissed (transitionContext: UIViewControllerContextTransitioning) {
//1 取出消失的view
let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
//2 执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
dismissView.alpha = 0.0
}) { (_) -> Void in
//移除view
dismissView.removeFromSuperview()
//完成动画
transitionContext.completeTransition(true)
}
}
//设置cell之间的间隔(这种方法是通过将collectionView的宽度增加来实现的)
override func loadView() {
super.loadView()
view.frame.size.width += 15
}
标签:
原文地址:http://blog.csdn.net/xf931456371/article/details/51278805