-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUICollectionViewExtension.swift
executable file
·104 lines (88 loc) · 3.1 KB
/
UICollectionViewExtension.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//
// UICollectionViewExtension.swift
//
// Created by Pramod Kumar on 04/04/18.
// Copyright © 2018 Pramod Kumar. All rights reserved.
//
import Foundation
import UIKit
//MARK:- UICollectionView Extension
extension UICollectionView {
func registerCell(nibName:String, bundle:Bundle? = nil, forCellWithReuseIdentifier:String? = nil){
let cellWithReuseIdentifier = forCellWithReuseIdentifier ?? nibName
self.register(UINib(nibName: nibName , bundle: bundle), forCellWithReuseIdentifier: cellWithReuseIdentifier)
}
func cell(forItem: AnyObject) -> UICollectionViewCell? {
if let indexPath = self.indexPath(forItem: forItem) {
return self.cellForItem(at: indexPath)
}
return nil
}
func indexPath(forItem: AnyObject) -> IndexPath? {
let itemPosition: CGPoint = forItem.convert(CGPoint.zero, to: self)
return self.indexPathForItem(at: itemPosition)
}
func indexPathsForElementsInRect(rect: CGRect) -> NSArray?{
let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect)
if let layoutAttributes = allLayoutAttributes, layoutAttributes.count > 0{
let indexPaths = NSMutableArray(capacity: layoutAttributes.count)
for layoutAttribute in layoutAttributes{
let indexPath = layoutAttribute.indexPath
indexPaths.add(indexPath)
}
return indexPaths
}
else{
return nil
}
}
func isItemPresentAt(index: IndexPath) -> Bool {
if index.section < self.numberOfSections {
if index.item < self.numberOfItems(inSection: index.section) {
return true
}
}
return false
}
func isSectionPresentAt(section: Int) -> Bool {
if section < self.numberOfSections {
return true
}
return false
}
func reloadItems(at: IndexPath) {
if self.isItemPresentAt(index: at) {
self.reloadItems(at: [at])
}
else {
self.reloadData()
}
}
func reloadSection(section: Int) {
if self.isSectionPresentAt(section: section) {
self.reloadSections(IndexSet(integer: section))
}
else {
self.reloadData()
}
}
///pull to refresh
func enablePullToRefresh(target: UIViewController, selector: Selector, tintColor: UIColor? = nil){
let refreshControl = UIRefreshControl()
refreshControl.backgroundColor = AppColor.black
refreshControl.addTarget(target, action: selector, for: UIControlEvents.valueChanged)
if let tColor = tintColor{
refreshControl.tintColor = tColor
}
self.alwaysBounceVertical = true
self.addSubview(refreshControl)
}
func endRefreshing(){
for view in self.subviews{
if let refreshControl = view as? UIRefreshControl{
refreshControl.endRefreshing()
break
}
}
}
}