总结要点

注意:
1:shouldPerformSegue(withIdentifier:sender:) -> bool 方法控制segue的效能
2: let index = selectedIcons.index(where:{$0.icon.name == deSelectedIcon.name})
index(where)条件返回index
3:snapshot生成快照
UIGraphicsBeginImageContext(bounds.size)
if let context = UIGraphicsGetCurrentContext(){
self.layer.render(in:context)
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return image
4:let indexPaths = collectionView.indexPathsForSelectedItems返回多个索引,所以在单选的情况下,通过indexPaths.first来获取
5:prepare(for:sender:) 与 shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool连用
6:@IBAction func unwindToHome(segue:UIStoryboardSegue){}//退出exit时link的方法(解除segue)


IconCollectionViewController.swift
IconDetailViewController.swift
IconCollectionViewCell.swift
Icon.swift
UIView+Snapshot.swift



IconCollectionViewController.swift

import UIKitprivate let reuseIdentifier = "Cell"class IconCollectionViewController: UICollectionViewController {private var iconSet: [Icon] = [ Icon(name: "Candle icon", imageName: "candle", description: "Halloween icons designed by Tania Raskalova.", price: 3.99, isFeatured: false),Icon(name: "Cat icon", imageName: "cat", description: "Halloween icon designed by Tania Raskalova.", price: 2.99, isFeatured: true),Icon(name: "dribbble", imageName: "dribbble", description: "Halloween icon designed by Tania Raskalova.", price: 1.99, isFeatured: false),Icon(name: "Ghost icon", imageName: "ghost", description: "Halloween icon designed by Tania Raskalova.", price: 4.99, isFeatured: false),Icon(name: "Hat icon", imageName: "hat", description: "Halloween icon designed by Tania Raskalova.", price: 2.99, isFeatured: false),Icon(name: "Owl icon", imageName: "owl", description: "Halloween icon designed by Tania Raskalova.", price: 5.99, isFeatured: true),Icon(name: "Pot icon", imageName: "pot", description: "Halloween icon designed by Tania Raskalova.", price: 1.99, isFeatured: false),Icon(name: "Pumkin icon", imageName: "pumkin", description: "Halloween icon designed by Tania Raskalova.", price: 0.99, isFeatured: false),Icon(name: "RIP icon", imageName: "rip", description: "Halloween icon designed by Tania Raskalova.", price: 7.99, isFeatured: false),Icon(name: "Skull icon", imageName: "skull", description: "Halloween icon designed by Tania Raskalova.", price: 8.99, isFeatured: false),Icon(name: "Sky icon", imageName: "sky", description: "Halloween icon designed by Tania Raskalova.", price: 0.99, isFeatured: false),Icon(name: "Toxic icon", imageName: "toxic", description: "Halloween icon designed by Tania Raskalova.", price: 2.99, isFeatured: false),Icon(name: "Book icon", imageName: "ic_book", description: "Colorful icon designed by Marin Begović.", price: 2.99, isFeatured: false),Icon(name: "Backpack icon", imageName: "ic_backpack", description: "Colorful icon designed by Marin Begović.", price: 3.99, isFeatured: false),Icon(name: "Camera icon", imageName: "ic_camera", description: "Colorful camera icon designed by Marin Begović.", price: 4.99, isFeatured: false),Icon(name: "Coffee icon", imageName: "ic_coffee", description: "Colorful icon designed by Marin Begović.", price: 3.99, isFeatured: true),Icon(name: "Glasses icon", imageName: "ic_glasses", description: "Colorful icon designed by Marin Begović.", price: 3.99, isFeatured: false),Icon(name: "Icecream icon", imageName: "ic_ice_cream", description: "Colorful icon designed by Marin Begović.", price: 4.99, isFeatured: false),Icon(name: "Smoking pipe icon", imageName: "ic_smoking_pipe", description: "Colorful icon designed by Marin Begović.", price: 6.99, isFeatured: false),Icon(name: "Vespa icon", imageName: "ic_vespa", description: "Colorful icon designed by Marin Begović.", price: 9.99, isFeatured: false)]@IBOutlet weak var shareButton: UIBarButtonItem!fileprivate var shareEnabled = falsefileprivate var selectedIcons:[(icon:Icon,snapshot:UIImage)] = []override func viewDidLoad() {super.viewDidLoad()}@IBAction func shareButtonTapped(_ sender: Any) {guard shareEnabled else {// 变更shareEnabled为YES并变更按钮文字为DoneshareEnabled = truecollectionView?.allowsMultipleSelection = trueshareButton.title = "Done"shareButton.style = UIBarButtonItemStyle.donereturn}// 确认是使用者至少有选择一个图片guard selectedIcons.count > 0  else {let alet = UIAlertController(title: "注意", message: "请选择分享的图片", preferredStyle: .alert)self.present(alet, animated: true) {alet.dismiss(animated: true, completion: nil)}return}// 取得所选图片的快照let snapshots = selectedIcons.map { $0.snapshot}// 建立分享用的动态视图控制器let activityController = UIActivityViewController(activityItems: snapshots, applicationActivities: nil)///typedef void (^UIActivityViewControllerCompletionWithItemsHandler)(UIActivityType activityType, BOOL completed, NSArray *returnedItems, NSError *activityError);activityController.completionWithItemsHandler = {(activityType, completed, returnedItems, activityError) in// 取消所有选取项目if let indexPaths = self.collectionView?.indexPathsForSelectedItems {for indexPath in indexPaths {self.collectionView?.deselectItem(at: indexPath, animated: false)}}// selectedIcons阵列中移除所有项目self.selectedIcons.removeAll(keepingCapacity: true)// 变更分享模式为NOself.shareEnabled = falseself.collectionView?.allowsMultipleSelection = falseself.shareButton.title = "Share"self.shareButton.style = UIBarButtonItemStyle.plain}present(activityController, animated: true, completion: nil)}/*很重要,注意点 因为segue是在每一个cell被按下时会被调用,但当app在分享模式下,我们不要触发这个segue,只要在单选模式时才需要触发它,*/override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {if identifier == "showIconDetail"{if shareEnabled {return false}}return true}@IBAction func unwindToHome(segue:UIStoryboardSegue){}override func prepare(for segue: UIStoryboardSegue, sender: Any?) {if segue.identifier == "showIconDetail"{if let indexPaths = collectionView?.indexPathsForSelectedItems{let destinationController = segue.destination as! IconDetailViewControllerdestinationController.icon = iconSet[indexPaths[0].row]collectionView?.deselectItem(at: indexPaths[0], animated: false)}}}// MARK: UICollectionViewDelegateoverride func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {// 检查分享模式是否已经启动,没有的话就离开这个方法guard shareEnabled else {return}// 使用indexPath来判断所选的项目并带入一个快照let selectedIcon = iconSet[indexPath.row]if let snapshot = collectionView.cellForItem(at: indexPath)?.snapshot {// 增加选中的item到arrayselectedIcons.append((icon: selectedIcon, snapshot: snapshot))}}override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {// 检查分享模式是否启动,没有的话就离开这个方法guard shareEnabled else {return}let deSelectedIcon = iconSet[indexPath.row]/* 找到所选图示的索引,这里我们使用索引方法并传递一个闭包.在闭包中我们对所选图示的名称与所选图示阵列的所有项目做比较,如果名称有符合的话,这个索引方法将会回传其索引值,用这个索引值移除这个item*/if let index = selectedIcons.index(where: {$0.icon.name == deSelectedIcon.name}){selectedIcons.remove(at: index)}}// MARK: UICollectionViewDataSourceoverride func numberOfSections(in collectionView: UICollectionView) -> Int {// Return the number of sectionsreturn 1}override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {// Return the number of itemsreturn iconSet.count}override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! IconCollectionViewCell// Configure the celllet icon = iconSet[indexPath.row]cell.iconImageView.image = UIImage(named: icon.imageName)cell.iconPriceLabel.text = "$\(icon.price)"cell.backgroundView = (icon.isFeatured) ? UIImageView(image: UIImage(named: "feature-bg")) : nilcell.selectedBackgroundView = UIImageView(image: UIImage(named: "icon-selected"))return cell}}

IconDetailViewController.swift

import UIKitclass IconDetailViewController: UIViewController {var icon:Icon?@IBOutlet weak var iconImageView: UIImageView!{didSet{iconImageView.image = UIImage(named: icon?.imageName ?? "")}}@IBOutlet weak var nameLabel: UILabel!{didSet{nameLabel.text = icon?.name}}@IBOutlet weak var descriptionLabel: UILabel!{didSet{descriptionLabel.text = icon?.descriptiondescriptionLabel.numberOfLines = 0}}@IBOutlet weak var priceLabel: UILabel!{didSet{if let icon = icon {priceLabel.text = "$\(icon.price)"}}}@IBAction func buyAction(_ sender: UIButton) {}
}

IconCollectionViewCell.swift

class IconCollectionViewCell: UICollectionViewCell {@IBOutlet var iconImageView: UIImageView!@IBOutlet var iconPriceLabel: UILabel!
}

Icon.swift

import Foundationstruct Icon {var name: String = ""var imageName = ""var description = ""var price: Double = 0.0var isFeatured: Bool = falseinit(name: String, imageName: String, description: String, price: Double, isFeatured: Bool) {self.name = nameself.imageName = imageNameself.description = descriptionself.price = priceself.isFeatured = isFeatured}
}

UIView+Snapshot.swift

import Foundation
import UIKitextension UIView {/*取得视图快照的方式:以视图的大小来建立一个点阵圆为主的图形内容(context),然后我们渲染(render)视图的Neri,并从中取得图片*/var snapshot : UIImage? {var image:UIImage? = nilUIGraphicsBeginImageContext(bounds.size)if let context = UIGraphicsGetCurrentContext(){self.layer.render(in: context)image = UIGraphicsGetImageFromCurrentImageContext()}UIGraphicsEndImageContext()return image}
}

collection中cell选中状态下分享图片的快照snapshot相关推荐

  1. Android ListView中CheckBox选中状态失效的最佳解决方案

    Android ListView中CheckBox选中状态失效: 在ListView中某一项滑到显示区外部的时候,重新划回来时其中的CheckBox的选中状态会重置,本文提出了一种解决方案,操作起来快 ...

  2. html 禁止选择与复制出现蓝色选中状态,禁止图片拖拽,隐藏鼠标,全屏状态下有效

    一.禁止选择与复制 js实现 ['contextmenu', 'selectstart', 'copy'].forEach(function(ev){document.addEventListener ...

  3. tomcat中实现特定路径下的图片的url访问Tomcat配置图片保存路径,图片不保存在项目路径下...

    使用Tomcat作为服务器的时候,如果不配置图片保存路径,将图片保存在项目路径下,那么再次打war包发布项目可能会造成图片的丢失,每次重启前将图片先保存再copy到服务器明显不方便,这时可以配置图片保 ...

  4. html中鼠标移动有下拉图片,JQuery自适应全屏图片滚动鼠标上下滑动效果代码

    特效描述:JQuery 自适应全屏 图片滚动 鼠标上下滑动效果.JQuery:全屏随鼠标滑动而滚动 代码结构 1. 引入JS 2. HTML代码 $(function(){ $('body,html' ...

  5. 【Linux 内核】编译 Linux 内核 ④ ( 打开 Linux 内核编译 菜单配置 |菜单配置中的光标移动与选中状态 | 保存配置 | 配置项帮助文档 )

    文章目录 一.打开 Linux 内核编译 菜单配置 二.菜单配置中的光标移动与选中状态 三.保存配置 四.配置项帮助文档 一.打开 Linux 内核编译 菜单配置 执行 make menuconfig ...

  6. 计算机锁屏之后QQ音乐停止播放了,MAC电脑如何在息屏状态下让QQ音乐能继续播放音乐...

    MAC电脑如何在息屏状态下让QQ音乐能继续播放音乐 一般MAC电脑息屏之后,大部分的应用都是会停止运行的,比如QQ音乐,就不会再播放音乐.今天小编就跟大家分享下MAC电脑如何在息屏状态下让QQ音乐能继 ...

  7. [Windows Phone 7]开发分享图片的插件(2)

    在WP7的picture hub中,选中一张图片,查看图片时,点击"-"菜单,点share-时,会出现一个菜单(这个菜单中就是可以对选中的图片进行分享或者处理的应用列表) 下面介绍 ...

  8. qt Android 按键事件,QT无窗口状态下对键盘事件的监听

    Question:最近在搞linux下的一个客户端项目,需要接收键盘事件,但是又不能有界面,这种情况怎么处理呢? int main(int argc, char *argv[]) { QApplica ...

  9. 解决el-checkbox选中状态更改问题

    目录 前言: 问题分析: 解决方式: 前言: 相信很多猿友都被el-checkbox选中状态更改的问题困扰的掉了不少头发!!!!!!!这玩意真的是坑啊!!今天,机缘巧合(认真研究)之下,终于解决了这个 ...

最新文章

  1. RDKit | 基于RDKit通过SMARTS定义反应模式来生成反应产物
  2. python开发安卓程序-如何使用python开发android应用
  3. GBRT(GBDT)(MART)(Tree Net)(Tree link)
  4. 处理文件和文件夹的模块---os
  5. 前端工程师后端转型实录
  6. 深圳php和java,深圳java技术培训学习(Java和PHP区别)
  7. 移动APP开发工作笔记001---Hbuilder连接苹果手机
  8. 超市对账源码php_[源码和文档分享]基于Java的在线购物系统的设计与实现
  9. 再分享一个零成本做文库代下载赚钱项目
  10. 汽车 php 深圳,深圳小汽车增量调控管理信息系统查询官网
  11. python爬不同图片分别保存在不同文件夹中的实现
  12. 生产制造工厂的十二项生产管理步骤
  13. 如何开发一个酷炫的mdx
  14. 新手上路--分享20个无版权的高清图库素材网站
  15. Z2021年全球家用自动血压计收入大约1018.7百万美元,预计2028年达到1194.2百万美元,2022至2028期间,年复合增长率CAGR为 %。同时2020年全球家用自动血压计销量大约 ,预计
  16. 关于json数组转List对象的问题
  17. python编写存储过程_存储过程 - msjaxuexi - 博客园
  18. 电影评论系统C语言,源代码电影评论
  19. Angular $q 完全指南
  20. Android平台根据分辨率计算屏幕尺寸,基于物理尺寸来验证手机和平板应用合并的可行性

热门文章

  1. 大三上期末复习(网络安全物联网概论安全协议软件工程)
  2. arduino nano烧录出错
  3. 【小河今学 | Bootstrap-v3+animate+wow】制作一个简单的响应式网站
  4. 企业微信直播服务器,企业微信直播平台的利用
  5. android Java 笔试考题
  6. 输入字符,如果是大写则转化为小写,如果是小写则转化为大写
  7. 浅谈简单线性回归(Simple linear regression)part3SEE,MSE,SSE的关系
  8. DAWG A Defense Against Cache Timing Attacks in Speculative Execution Processors
  9. 基本软件项目管理考试题目
  10. 基于springboot的校园二手交易系统-JAVA【数据库设计、论文、源码、开题报告】