import
UIKit
class
ViewController
:
UIViewController
{
var
flowLayout:
UICollectionViewFlowLayout
!
var
linearLayput:
LinearCollectionViewLayout
!
var
collectionView:
UICollectionView
!
let
CellIdentifier
=
"myCell"
var
images = [
"c#.png"
,
"html.png"
,
"java.png"
,
"js.png"
,
"php.png"
,
"react.png"
,
"ruby.png"
,
"swift.png"
,
"xcode.png"
]
override
func
viewDidLoad() {
super
.viewDidLoad()
initCollectionView()
let
tapRecognizer =
UITapGestureRecognizer
(target:
self
,
action: #selector(
ViewController
.handleTap(_:)))
collectionView.addGestureRecognizer(tapRecognizer)
}
private
func
initCollectionView() {
flowLayout =
UICollectionViewFlowLayout
()
flowLayout.itemSize =
CGSize
(width: 60, height: 60)
flowLayout.sectionInset =
UIEdgeInsets
(top: 74, left: 0, bottom: 0, right: 0)
linearLayput =
LinearCollectionViewLayout
()
collectionView =
UICollectionView
(frame: view.bounds,
collectionViewLayout: linearLayput)
collectionView.delegate =
self
collectionView.dataSource =
self
collectionView.backgroundColor = .white
let
cellXIB =
UINib
.
init
(nibName:
"MyCollectionViewCell"
, bundle:
Bundle
.main)
collectionView.register(cellXIB, forCellWithReuseIdentifier:
CellIdentifier
)
view.addSubview(collectionView)
}
func
handleTap(_ sender:
UITapGestureRecognizer
){
if
sender.state ==
UIGestureRecognizerState
.ended{
let
tapPoint = sender.location(
in
:
self
.collectionView)
if
let
indexPath =
self
.collectionView.indexPathForItem(at: tapPoint) {
self
.collectionView.performBatchUpdates({ () ->
Void
in
self
.collectionView.deleteItems(at: [indexPath])
self
.images.remove(at: indexPath.row)
}, completion:
nil
)
}
else
{
let
index = 0
images.insert(
"xcode.png"
, at: index)
self
.collectionView.insertItems(at: [
IndexPath
(item: index, section: 0)])
}
}
}
@IBAction
func
changeLayout(_ sender:
Any
) {
self
.collectionView.collectionViewLayout.invalidateLayout()
let
newLayout = collectionView.collectionViewLayout
.isKind(of:
LinearCollectionViewLayout
.
self
) ? flowLayout : linearLayput
collectionView.setCollectionViewLayout(newLayout!, animated:
true
)
}
override
func
didReceiveMemoryWarning() {
super
.didReceiveMemoryWarning()
}
}
extension
ViewController
:
UICollectionViewDataSource
{
func
numberOfSections(
in
collectionView:
UICollectionView
) ->
Int
{
return
1
}
func
collectionView(_ collectionView:
UICollectionView
,
numberOfItemsInSection section:
Int
) ->
Int
{
return
images.count
}
func
collectionView(_ collectionView:
UICollectionView
,
cellForItemAt indexPath:
IndexPath
) ->
UICollectionViewCell
{
let
cell = collectionView.dequeueReusableCell(withReuseIdentifier:
CellIdentifier
,
for
: indexPath)
as
!
MyCollectionViewCell
cell.imageView.image =
UIImage
(named: images[indexPath.item])
return
cell
}
}
extension
ViewController
:
UICollectionViewDelegate
{
}
请发表评论