当前位置:网站首页>Photo selector collectionview
Photo selector collectionview
2022-07-07 05:24:00 【Hanyang Li】
1. Definition PicturePickerController
import UIKit
// reusable Cell
private let PicturePickerCellId = "PicturePickerCellId"
// Maximum number of selected photos
private let PicturePickerMaxCount = 8
//MARK: - Photo picker
class PicturePickerController: UICollectionViewController {
// Matching array
lazy var pictures = [UIImage]()
// The photo index selected by the current user
private var selectedIndex = 0
//MARK: - Constructors
init(){
super.init(collectionViewLayout: PicturePickerLayout())
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// stay collectionViewController in collectionView != view
override func viewDidLoad() {
super.viewDidLoad()
//self.collectionView.backgroundColor = .orange
self.collectionView!.register(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)
}
// Photo selector layout
private class PicturePickerLayout: UICollectionViewFlowLayout{
override func prepare() {
// iOS 9.0 after ,iPad Support split screen , It is not recommended to rely too much on UIScreen As a layout reference
super.prepare()
let count = 4.0
let margin = UIScreen.main.scale * 4
let w = (collectionView!.bounds.width - (count + 1) * margin) / count
itemSize = CGSize(width: w, height: w)
sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
minimumLineSpacing = margin
minimumInteritemSpacing = margin
}
}
}
2. Extended classification , Data source implementation
extension PicturePickerController{
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// Make sure there is a plus button at the end If it reaches the upper limit , No display + Button pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
return pictures.count + 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PicturePickerCellId, for: indexPath) as! PicturePickerCell
cell.pictureDelegate = self
cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
cell.hiddenButton = (indexPath.item == PicturePickerMaxCount)
return cell
}
}
3. Realization Cell Medium proxy method
//MARK: - PicturePickerCellDelegate
extension PicturePickerController: PicturePickerCellDelegate{
func picturePickerCellDidAdd(cell: PicturePickerCell) {
// Determine whether to allow access to the album
/**
PhotoLibrary Saved photos + Synced photos
SavedPhotosAlbum Saved photos / Screenshot of the screen / Taking pictures
*/
if !UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
print(" Unable to access Photo Gallery ")
return
}
// Record the photo index selected by the current user
selectedIndex = collectionView!.indexPath(for: cell)?.item ?? 0
let picker = UIImagePickerController()
picker.modalPresentationStyle = .fullScreen
picker.delegate = self
//picker.allowsEditing = true
present(picker, animated: true)
}
func picturePickerCellDidRemove(cell: PicturePickerCell) {
//1. Get photo index
let indexPath = collectionView.indexPath(for: cell)!
//2. Determine whether the index exceeds the upper limit
if indexPath.item >= pictures.count{
return
}
collectionView.performBatchUpdates {
//3. Delete data
pictures.remove(at: indexPath.item)
//4. Animation refresh data
collectionView.deleteItems(at: [indexPath])
} completion: { finished in
//5. The refresh data
self.collectionView.reloadData()
}
}
}
4.UIImagePickerController Abide by the agreement
//MARK: - UIImagePickerController Abide by the agreement
extension PicturePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
/// Photo selection complete
/// - Parameters:
/// - picker: Photo selection controller
/// - info: info Dictionaries
/// - Tips : Once the proxy method is implemented , Must oneself dismiss
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
/**
If you use cocos2dx To develop a ‘ Blank template ’ game , Memory footprint 70M iOS UI A blank application for , Probably 19M
General applications , In memory 100M Both sides are acceptable , No matter how high you are, you need to pay attention
*/
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let scaleImage = image.scaleToWith(width: 600)
// Add image to array
// Judge whether the currently selected index exceeds the array
if selectedIndex >= pictures.count{
pictures.append(scaleImage)
}else{
pictures[selectedIndex] = scaleImage
}
// Release the controller
dismiss(animated: true) {
// refresh the view
self.collectionView.reloadData()
}
}
}
5.PicturePickerCellDelegate agent
///PicturePickerCellDelegate agent
/// If the agreement includes optional Function of , The protocol needs to use @objc modification
@objc
protocol PicturePickerCellDelegate: NSObjectProtocol{
/// Add photo
@objc optional func picturePickerCellDidAdd(cell: PicturePickerCell)
/// Remove the photo
@objc optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}
6. Photo selection Cell
// Photo selection Cell
class PicturePickerCell: UICollectionViewCell{
// Photo selection agent
weak var pictureDelegate: PicturePickerCellDelegate?
var image: UIImage? {
didSet{
addButton.setImage(image ?? UIImage(named: "compose_pic_add"), for: .normal)
// Hide delete button image == nil Is to add a new button
removeButton.isHidden = (image == nil)
}
}
var hiddenButton: Bool? {
didSet{
addButton.isHidden = hiddenButton ?? false
}
}
//MARK: - Monitoring methods
/// Add photo
@objc func addPicture(){
pictureDelegate?.picturePickerCellDidAdd?(cell: self)
}
/// Remove the photo
@objc func removePicture(){
pictureDelegate?.picturePickerCellDidRemove?(cell: self)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Setting controls
private func setupUI(){
//1. add controls
contentView.addSubview(addButton)
contentView.addSubview(removeButton)
//2. Setting up layout
addButton.frame = bounds
removeButton.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.top)
make.right.equalTo(contentView.snp.right)
}
//3. Monitoring methods
addButton .addTarget(self, action: #selector(addPicture), for: .touchUpInside)
removeButton.addTarget(self, action: #selector(removePicture), for: .touchUpInside)
//4. Set fill mode
addButton.imageView?.contentMode = .scaleAspectFill
}
//MARK: - Lazy load control
/// Add a button
private lazy var addButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
/// Delete button
private lazy var removeButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}
7. design sketch
边栏推荐
- 模拟线程通信
- Let f (x) = Σ x^n/n^2, prove that f (x) + F (1-x) + lnxln (1-x) = Σ 1/n^2
- 基于 hugging face 预训练模型的实体识别智能标注方案:生成doccano要求json格式
- batch size设置技巧
- Development thoughts of adding new requirements in secondary development
- 照片选择器CollectionView
- Is PMP really useful?
- 高级程序员必知必会,一文详解MySQL主从同步原理,推荐收藏
- Auto.js 获取手机所有app名字
- Sorry, I've learned a lesson
猜你喜欢
No experts! Growth secrets for junior and intermediate programmers and "quasi programmers" who are still practicing in Universities
实现网页内容可编辑
基于 hugging face 预训练模型的实体识别智能标注方案:生成doccano要求json格式
Dynamically generate tables
Longest palindrome substring (dynamic programming)
最长回文子串(动态规划)
What changes will PMP certification bring?
PMP证书有没有必要续期?
window定时计划任务
Harmonyos fourth training
随机推荐
batch size设置技巧
《2》 Label
Leetcode (46) - Full Permutation
Auto.js 获取手机所有app名字
SQL injection cookie injection
【js组件】自定义select
2039: [Bluebridge cup 2022 preliminaries] Li Bai's enhanced version (dynamic planning)
[opencv] image morphological operation opencv marks the positions of different connected domains
实现网页内容可编辑
数字化创新驱动指南
Pytest testing framework -- data driven
全链路压测:影子库与影子表之争
利用OPNET进行网络单播(一服务器多客户端)仿真的设计、配置及注意点
【QT】自定义控件-Loading
阿里云的神龙架构是怎么工作的 | 科普图解
最长公共子序列(LCS)(动态规划,递归)
np. random. Shuffle and np Use swapaxis or transfer with caution
利用OPNET进行网络任意源组播(ASM)仿真的设计、配置及注意点
pmp真的有用吗?
Under the trend of Micah, orebo and apple homekit, how does zhiting stand out?