Items in UICollectionView disappeared on scrolling - ios

I have an UICollectionViewController which will be displayed both on its own full screen mode as well as in a pop-up view of another controller. The full screen mode works perfectly. However, in the pop-up mode, all items disappears after the user scroll the content up and down for a few times (sometimes more than 10 times, but also happen at the first or second time)
let vc = storyboard.instantiateViewController(
withIdentifier: "myCollectionView") as? MyColle ctionViewController
// set up the overlap in the parent controller
let bounds = CGRect(x: x + 22, y: parentFrame.origin.y + dy,
width: width, height: parentFrame.height - dy - 10)
overlayView = UIView(frame: bounds)
overlayView!.layer.cornerRadius = 5.0
overlayView!.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 0.4)
self.view.addSubview(overlayView!)
vc.showAsPopup(overlayView!)
// in MyCollectionViewController, add itself to the parent popup view
func showAsPopup(_ parentView: UIView) {
view.backgroundColor = UIColor.red // test color to show the view is never gone
view.layer.cornerRadius = 5.0
collectionView?.backgroundColor = UIColor.clear
collectionView?.layer.cornerRadius = 5.0
parentView.addSubview(view)
view.frame = CGRect(x: 0, y: 20,
width: parentView.frame.width,
height: parentView.frame.height - 20)
NSLog("my view bounds after: \(view.frame.origin.x) \(view.frame.origin.y)")
NSLog(" : \(view.frame.width)x\(view.frame.height)")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
NSLog("\(items.count) items in section \(section)")
return items.count
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenRect = view.bounds
let scale = UIScreen.main.scale
let width = screenRect.size.width - 20
return CGSize(width: width, height: 45 * scale)
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = items[indexPath.item]
let cellId = "RCCell_\(item.id)"
NSLog("creating cell \(cellId)")
// Register cell classes
self.collectionView!.register(RemoteControlViewCell.self,
forCellWithReuseIdentifier: cellId)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId,
for: indexPath) as! RemoteControlViewCell
// Configure the cell, override the icon in Cell
cell.itemId = item.id
cell.itemIcon.image = item.icon
cell.itemDescriptionLabel.text = item.description
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 12.5, left: 0, bottom: 12.5, right: 0)
}
override func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
NSLog("removed cell at \(indexPath.row)")
}
// MyCollectionViewCell
override init(frame: CGRect) {
super.init(frame: frame)
let scale = UIScreen.main.scale
NSLog("Cell frame w: \(frame.size.width) h: \(frame.size.height), scale \(scale)")
let spacing = CGFloat(10)
contentView.backgroundColor = UIColor.white
contentView.layer.cornerRadius = 5
contentView.layer.masksToBounds = true
itemIcon = UIImageView(frame: CGRect(x: spacing, y: spacing,
width: CGFloat(24.0), height: CGFloat(24.0)))
itemIcon.contentMode = UIViewContentMode.scaleAspectFit
contentView.addSubview(itemIcon)
NSLog("icon w: \(itemIcon.frame.size.width)")
let labelX = spacing + 5 + itemIcon.frame.size.width
let font = UIFont.systemFont(ofSize: 20)
itemDescriptionLabel = UILabel(
frame: CGRect(x: labelX, y: spacing,
width: frame.size.width - labelX - spacing,
height: font.lineHeight))
itemDescriptionLabel.textColor = UIColor(colorLiteralRed: 0x66 / 255.0, green: 0x66 / 255.0, blue: 0x66 / 255.0, alpha: 1.0)
moduleDescriptionLabel.font = font
contentView.addSubview(itemDescriptionLabel)
NSLog("item desc \(String(describing: itemDescriptionLabel.text)) w: \(itemDescriptionLabel.frame.size.width)")
}
I tried changing the background color of the collectionView to visible and can see that the collect view itself was never gone even though the items disappeared. I also added logging to the collectionView() callback methods and found that they were never called again after the initial view presentation.
What could cause the items to disappear during scrolling?

Try using prepareForReuse in RemoteControlViewCell class
override func prepareForReuse() {
itemId = ""
itemIcon.image = nil
itemDescriptionLabel.text = ""
}

Related

Unexpected behavior with nested collection views with constraints (Swift 4)

I have a cell in a tableview that contains a horizontal paging collection view.
Inside each page of this collection view there is a vertical collection view.
In order to avoid a "scroll-in-scroll" problem, I disabled vertical scrolling in the vertical collection views.
The vertical collection view's cell count is not static and can be any number.
So this creates a problem: the collection view (you'll have to ask me for clarification about which one) won't fit properly into the table view's cell anymore.
To solve this, I changed the table view's cell height by changing the constraints in the storyboard... but the problem remains.
Here is an image to help illustrate the problem:
and here is my code:
class myTBViewController: UITableViewController , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 10 {
return 2
} else {
return 30
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView.tag == 10 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mainPages", for: indexPath) as! mainPages
cell.backgroundColor = UIColor.yellow
cell.listCV.clipsToBounds = true
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "showAdvCell", for: indexPath) as! showAdvCell
cell.backgroundColor = UIColor.red
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
if collectionView.tag == 10 {
let collectionViewHeight = collectionView.frame.height
let itemsHeight = collectionView.contentSize.height
let topInset = ( collectionViewHeight - itemsHeight ) / 4
return UIEdgeInsetsMake(topInset ,0, 0 , 0)
} else {
let collectionViewHeight = collectionView.frame.height
let itemsHeight = CGFloat(80)
let topInset = ( collectionViewHeight - itemsHeight ) / 4
return UIEdgeInsetsMake(topInset ,0, 0 , 0)
}
}
var headerSegment = UISegmentedControl()
override func viewDidLoad() {
super.viewDidLoad()
headerSegment.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 30)
let items = ["فروشگاه ها", "دیوار"]
headerSegment = UISegmentedControl(items: items)
headerSegment.selectedSegmentIndex = 0
headerSegment.addTarget(self, action: #selector(selectPage), for: UIControlEvents.valueChanged)
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200)
let headerImageView = UIImageView(frame: frame)
let image: UIImage = UIImage(named: "1")!
headerImageView.image = image
let frame3 = CGRect(x: 0, y: 0, width: 80, height: 80)
let headerImageView2 = UIImageView(frame: frame3)
let image2: UIImage = UIImage(named: "1")!
headerImageView2.image = image2
headerSegment.addSubview(headerImageView2)
headerSegment.bringSubview(toFront: headerImageView2)
headerImageView2.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 200)
headerSegment.frame = CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width + 10 , height: 40)
headerSegment.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 200)
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 230))
let headerSegmentView = UIView(frame : CGRect(x: 0, y: 200, width: UIScreen.main.bounds.width, height: 40))
headerSegmentView.center = headerSegment.center
headerSegmentView.backgroundColor = UIColor.white
mainView.addSubview(headerImageView)
mainView.bringSubview(toFront: headerImageView)
mainView.addSubview(headerSegmentView)
mainView.bringSubview(toFront: headerSegmentView)
mainView.addSubview(headerSegment)
mainView.bringSubview(toFront: headerSegment)
mainView.addSubview(headerImageView2)
mainView.bringSubview(toFront: headerImageView2)
self.tableView.tableHeaderView = mainView
headerImageView2.layer.borderWidth = 2
headerImageView2.layer.masksToBounds = false
headerImageView2.layer.borderColor = UIColor.init(white: 255/255, alpha: 0.3).cgColor
headerImageView2.layer.cornerRadius = headerImageView2.frame.height/2
headerImageView2.clipsToBounds = true
}
#objc func selectPage() {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "myTBViewCell") as! myTBViewCell
switch headerSegment.selectedSegmentIndex {
case 0:
print("0")
cell.myTBCollectionView.scrollToItem(at:IndexPath(item: 0, section: 0), at: .top, animated: false)
case 1:
print("1")
cell.myTBCollectionView.scrollToItem(at:IndexPath(item: 1, section: 0), at: .top, animated: false)
default:
print("0")
cell.myTBCollectionView.scrollToItem(at:IndexPath(item: 0, section: 0), at: .top, animated: false)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
return 600
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "myTBViewCell", for: indexPath) as! myTBViewCell
return cell
}
}
I have a similar Problem , finally, I have solved it by creating a height Constraint of CollectionView.
than setting CollectionView height Constraint based on CollectionView ContentSize.
self.collectionViewHeight.constant = self.recentCollectionView.collectionViewLayout.collectionViewContentSize.height
the alternative approach is to override systemLayoutSizeFitting method of tableViewCell
ex:
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
self.tagCollectionView.layoutIfNeeded()
return self.tagCollectionView.collectionViewLayout.collectionViewContentSize
}
in addition you don't need to return fixed 600 height in your table view delegate heightForRowAtIndexPath

Why is only image in first cell updated while the rest of the cells in uicollectionview not updated. ios swift

I'm trying to get 3 icons on the top bar.
import UIKit
class SectionHeader: UICollectionReusableView {
private let telButtonCellId = "TelButtonCell"
private let searchBarCellId = "SearchBarCell"
private let notificationButtonCellId = "NotificationButtonCell"
// MARK: - Properties
#IBOutlet weak var collectionView: UICollectionView!
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
self.collectionView.register(UINib(nibName:notificationButtonCellId, bundle: nil), forCellWithReuseIdentifier: notificationButtonCellId)
self.collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width*0.2) // this is need to set the size of the collection view
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
extension SectionHeader : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: notificationButtonCellId, for: indexPath) as! NotificationButtonCell
var image = UIImage(named: "globe")
cell.imageView.image=image?.addImagePaddingShift(x: 20 , y: 20,shiftX: 0, shiftY: 10)
cell.imageView.contentMode = .scaleAspectFit
cell.imageView.bounds=cell.bounds
cell.imageView.center = cell.center;
cell.backgroundColor = UIColor.lightGray
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frameWidth = UIScreen.main.bounds.width
let frameHeight = UIScreen.main.bounds.width*0.2
return CGSize(width: frameWidth*0.15, height: frameHeight*1.0)
}
So only the first cell will have the globe displayed.
the rest of the 2 cells are empty even though i can change the background colour.
The SectionHeader is a nib
The imageView is subview of the cell, that needs to be with its size as I see. So it needs its frame (its position in relation to its superview coordinate system - the cell) to be set to the height and width of the cell with origin (0,0). The bounds of the cell provide these dimensions so the answer can be
cell.imageView.frame = cell.bounds
or better
cell.imageView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)

UICollectionViewCell is reordered or disappear on scroll

I have a problem with UICollectionView. I created a collection with FlowLayout and I'm trying to resize only second item to make it width to 2xcellWidth. It's ok when View is appear, but after that, when I'm scrolling and back to top, my cell are disappear, reorder or change it width. It's totally weird behave.
So to be clear: I created collection view, scroll to bottom and when I back to top, I see my cells are in some weird place like this:
before:
after:
class MapEventsViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
var collectionView: UICollectionView!
let screenWidth = UIScreen.main.bounds.width
let options = [Options(id: "", value: "28-03-2017 10:54:01"),
Options(id: "", value: "Berlin Strasse 6A 00-000, Berlin", isDoubled: true),
Options(id: "Status", value: "-"),
Options(id: "Prędkość", value: "40km/h"),
Options(id: "Licznik", value: "250000km"),
Options(id: "Napięcie", value: "15V")]
override func viewDidLoad() {
super.viewDidLoad()
view.frame.size.height = 170
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 1)
layout.minimumLineSpacing = 1
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .vertical
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(MapEventCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = UIColor.white
collectionView.isScrollEnabled = true
collectionView.alwaysBounceVertical = true
collectionView.autoresizingMask = UIViewAutoresizing.flexibleWidth
collectionView.backgroundColor = UIColor.init(white: 0.90, alpha: 1.0)
collectionView.showsVerticalScrollIndicator = true
self.view.addSubview(collectionView)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return options.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MapEventCell
cell.awakeFromNib()
cell.id.font = UIFont.systemFont(ofSize: 12)
cell.value.font = UIFont.boldSystemFont(ofSize: 14)
cell.backgroundColor = UIColor.white
if indexPath.row == 0{
cell.value.font = UIFont.systemFont(ofSize: 10)
cell.value.frame.origin.y -= 6
}
if indexPath.row == 1{
cell.value.font = UIFont.systemFont(ofSize: 10)
cell.value.frame.origin.y -= 6
}
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let thisCell = cell as! MapEventCell
thisCell.id.text = options[indexPath.item].id
thisCell.value.text = options[indexPath.item].value
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// print("sizeForItemAt")
let cellWidth = UIScreen.main.bounds.width / 3 - 1
if options[indexPath.item].isDoubled{
return CGSize(width: cellWidth * 2 + 1, height: 40)
}
return CGSize(width: cellWidth, height: 40)
}
}
class MapEventCell: UICollectionViewCell{
var id: UILabel = UILabel()
var value: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
print("addViews")
id.frame = CGRect(x: 0, y: 0, width: contentView.frame.width, height: 16)
id.textAlignment = .center
value.frame = CGRect(x: 0, y: 16, width: contentView.frame.width, height: 20)
value.textAlignment = .center
// id.font = UIFont.systemFont(ofSize: 12)
id.textColor = UIColor.lightGray
// value.font = UIFont.boldSystemFont(ofSize: 14)
contentView.addSubview(id)
contentView.addSubview(value)
}
override func prepareForReuse() {
id.removeFromSuperview()
value.removeFromSuperview()
}
}
UPDATE
I've solved this problem by calculating frame of each element in cell at CellForItemAt indexPath. So now it looks like this (and worked):
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MapEventCell
cell.awakeFromNib()
cell.backgroundColor = UIColor.white
if indexPath.section == 0{
cell.value.frame = CGRect(x: 0, y: 0, width: (screenWidth / 3), height: 30)
if options[indexPath.item].isDoubled {
cell.value.frame = CGRect(x: 0, y: 0, width: (screenWidth / 3) * 2 - 2, height: 30)
cell.value.textAlignment = .center
}
cell.id.isHidden = true
cell.value.font = UIFont.systemFont(ofSize: 10)
}else{
//cell.frame = CGRect(x: 0, y: 0, width: (screenWidth / 3) - 1, height: 40)
cell.id.isHidden = false
cell.id.font = UIFont.systemFont(ofSize: 10)
cell.value.font = UIFont.boldSystemFont(ofSize: 12)
}
return cell
}
But now I'm not sure is it good solving. I know that every time cells are reusing, so my question is, are there better solutions for this problem?

Display cards in overlap using UICollectionView - Swift3

I'm trying to arrange cards into UICollectionView in a overlap manner as like below,
i am using https://github.com/ra1028/RAReorderableLayout to order items into UICollectionView cell with drag drop gesture.
now the cards displays without overlap and drag drop works fine,
Mycode:
class HandController: UIViewController, RAReorderableLayoutDelegate, RAReorderableLayoutDataSource {
let game = Game.sharedInstance
#IBOutlet weak var collectionView: UICollectionView!
private var books = [CardViewButton]()
override func viewDidLoad() {
debugPrint("?? Hand300Controller ?...")
super.viewDidLoad()
collectionView.backgroundColor = UIColor.clear
title = "RAReorderableLayout"
collectionView.register(BookCell.self, forCellWithReuseIdentifier: "cell")
collectionView.delegate = self
collectionView.dataSource = self
(collectionView.collectionViewLayout as! RAReorderableLayout).scrollDirection = .horizontal
let aScalars = "A".unicodeScalars
let zScalars = "Z".unicodeScalars
let aAsciiCode = aScalars[aScalars.startIndex].value
let zAsciiCode = zScalars[zScalars.startIndex].value
//books = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14"]/*
game.deck?.shuffleRandom()
// containerForCardTable.addSubview(Game.sharedInstance.table.cardTableView)
for index in 0...12{
//print(game.deck?.cards[index].value)
game.deck?.cards[index].isFaceUp = true
books.append(((game.deck?.cards[index])?.cardView.cardViewButton)!)
}
}
// collectionView delegate datasource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return books.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 60.0, height: 100.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 20.0, 0, 20.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 15
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: BookCell
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! BookCell
//book = CardView(frame:CGRect(x: 15.0, y: 30.0, width: bounds.width - 16.0, height: 30.0),)
cell.book = CardViewButton(frame:books[(indexPath as NSIndexPath).item].frame,value:books[(indexPath as NSIndexPath).item].value,id:books[(indexPath as NSIndexPath).item].id,isFaceUp : true)
//cell.book = books[(indexPath as NSIndexPath).item]
cell.contentView.addSubview(cell.book)
return cell
}
func collectionView(_ collectionView: UICollectionView, at: IndexPath, willMoveTo toIndexPath: IndexPath) {
let temp = books[at.row]
books[at.row] = (books[toIndexPath.row])
books[toIndexPath.row] = temp
}
func collectionView(_ collectionView: UICollectionView, at: IndexPath, didMoveTo toIndexPath: IndexPath) {
// let book = books.remove(at: (toIndexPath as NSIndexPath).item)
// books.insert(book, at: (toIndexPath as NSIndexPath).item)
}
func scrollTrigerEdgeInsetsInCollectionView(_ collectionView: UICollectionView) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 50, 0, 50)
}
func scrollSpeedValueInCollectionView(_ collectionView: UICollectionView) -> CGFloat {
return 15.0
}
}
class BookCell: UICollectionViewCell {
private var backCoverView: UIView!
private var pagesView: UIView!
private var frontCoverView: UIView!
private var bindingView: UIView!
var book: CardViewButton!
/*var book: CardView? {
didSet {
titleLabel.text = book?.title
color = book?.color
}
}*/
var color: UIColor? {
didSet {
backCoverView.backgroundColor = getDarkColor(color, minusValue: 20.0)
frontCoverView.backgroundColor = color
bindingView.backgroundColor = getDarkColor(color, minusValue: 50.0)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
override func prepareForReuse() {
super.prepareForReuse()
// book.
}
private func configure() {
backCoverView = UIView(frame: bounds)
backCoverView.backgroundColor = getDarkColor(UIColor.white, minusValue: 20.0)
backCoverView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
pagesView = UIView(frame: CGRect(x: 15.0, y: 0, width: bounds.width - 25.0, height: bounds.height - 5.0))
pagesView.backgroundColor = UIColor.white
pagesView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
frontCoverView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height - 10.0))
frontCoverView.backgroundColor = UIColor.red
frontCoverView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bindingView = UIView(frame: CGRect(x: 0, y: 0, width: 15.0, height: bounds.height))
bindingView.backgroundColor = getDarkColor(backCoverView?.backgroundColor, minusValue: 50.0)
bindingView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bindingView.layer.borderWidth = 1.0
bindingView.layer.borderColor = UIColor.black.cgColor
}
private func getDarkColor(_ color: UIColor?, minusValue: CGFloat) -> UIColor? {
if color == nil {
return nil
}
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
color!.getRed(&r, green: &g, blue: &b, alpha: &a)
r -= max(minusValue / 255.0, 0)
g -= max(minusValue / 255.0, 0)
b -= max(minusValue / 255.0, 0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
How to arrange the cards in overlap display and drag drop work for overlap design

How make UICollectionView with 2 columns, different cells heights but with equal margins (all 4)?

I have one problem with UICollectionView. I need to make UICollectionView with these properties:
All cells in UICollectionView have same width.
Cells in UICollectionView do NOT have same height.
UICollectionView have two columns.
All margins between all cells must be the 20px.
I can not implement 2 and 4 in the same time. Just colour cells (no need to put any object in cells).
I need solution in Swift.
Here is screenshot http://i.imgur.com/ovmdyla.png and my code:
let imagesNames = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
func setUpUI(){
let flowLayoutForCV = UICollectionViewFlowLayout()
flowLayoutForCV.sectionInset = UIEdgeInsets(top: 10, left: UIScreen.mainScreen().bounds.width * 0.03, bottom: 10, right: UIScreen.mainScreen().bounds.width * 0.03)
let cV = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height), collectionViewLayout: flowLayoutForCV)
cV.backgroundColor = UIColor.whiteColor()
cV.dataSource = self
cV.delegate = self
cV.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
self.view.addSubview(cV)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesNames.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cellID", forIndexPath: indexPath)
let red: CGFloat = CGFloat(arc4random_uniform(255)) / 255.0
let green: CGFloat = CGFloat(arc4random_uniform(255)) / 255.0
let blue: CGFloat = CGFloat(arc4random_uniform(255)) / 255.0
cell.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: UIScreen.mainScreen().bounds.width * 0.455, height: CGFloat(arc4random_uniform(250)) + 50)
}

Resources