CollectionView don't update visible cell - swift

Good afternoon!
Faced with this problem, there is a collection in which cells in the whole screen
the cell is configured with data,
and there are events inside the cell that make the collection reload,
it is not possible to make a check, if the cell is now visible, it is not necessary to update it completely, but only part of the data, I do not yet understand how to do it, can someone be able to prompt?!))
Test project))
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var collectionViwe: UICollectionView!
let dataSource = [1,2,3,4,5,6,7,8,9]
override func viewDidLoad() {
super.viewDidLoad()
collectionViwe.isPagingEnabled = true
collectionViwe.register(Cell.self, forCellWithReuseIdentifier: "Cell")
// Do any additional setup after loading the view.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
let text = String(dataSource[indexPath.row])
if cell.label.text != text {
cell.label.text = text
cell.label.backgroundColor = .random()
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return view.frame.size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.reloadData()
}
}
class Cell: UICollectionViewCell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.backgroundColor = .red
addSubview(label)
label.frame = CGRect(x: 36, y: 36, width: 200, height: 100)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0)
}
}

Related

Why won't my swift collection view show anything

I want to make a simple collection view just showing some pictures but the cells wont show
import UIKit
final class HomePageViewController: UICollectionViewController {
// MARK: - Properties
override func loadView() {
super.loadView()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
])
self.collectionView = collectionView
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.backgroundColor = .white
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.register(HomePageCell.self, forCellWithReuseIdentifier: "HomePageCell")
}
// MARK: - Private
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomePageCell", for: indexPath) as! HomePageCell
cell.Picture.image = UIImage(named: "songpic-1")
return cell
}
}
extension HomePageViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.size.width - 16, height: 200)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 8
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 8, left: 8, bottom: 8, right: 8)
}
}
import UIKit
class HomePageCell: UICollectionViewCell {
#IBOutlet weak var Picture: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
let Picture = UIImageView(frame: .zero)
Picture.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(Picture)
NSLayoutConstraint.activate([
Picture.topAnchor.constraint(equalTo: self.contentView.topAnchor),
Picture.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
Picture.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor),
Picture.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor),
])
self.contentView.backgroundColor = .lightGray
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("Interface Builder is not supported!")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
You can delete/comment your loadView() implementation and things should work just fine. You will still get a UICollectionView to work with.
The loadView() implementation is supposed to provide a UIView instance that's to be assigned to UIViewController.view property. In your implementation however, we are using it via self.view directly without assigning it first.
From UIViewController.loadView() docs -
You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not call super.
What to do if this still doesn't show up?
Check using View Hierarchy Debugger that at run time your collectionView has non-zero width & height values. If any of the width OR height is zero, you will run into this issue.

UICollectionView in UIControl - delegate & datasource

I've added a UICollectionView to a UIControl (which is being called in a UITableViewController section header) and the UICollectionView is appearing (background color shows), but the datasource and delegate seem to be ignored - no cells are showing and a print statement in my dequeueReusableCell function isn't being called (but one in the UIControl init method is. Can you tell me what I'm missing here?
My UIControl:
// Stripped down code
final class My_Control: UIControl {
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(myCV)
}
private let myCV: Custom_CV = {
let cv: Custom_CV = Custom_CV()
return cv
}()
}
My Collection View:
final class Custom_CV: UIControl, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
cell.backgroundColor = .red
print("Building cell") // Not being called
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 72.0, height: 72.0)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//
}
private let cellIdentifier: String = "cellIdentifier"
private let collectionView: UICollectionView = {
let layout: UICollectionViewLayout = UICollectionViewLayout()
let collectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .white
return collectionView
}()
}
I think I'm missing something obvious, but I don't see it. I'm expecting to see 10 red squares and 10 print statements, but I get nothing there. But as I said - it's definitely being called because the a print statement in My_CV's init was being called, and I can see the .white background for the collectionview in My_Control.

Autolayout strange behaviour on Ipad

collection view getting right size with auto layout but view size on collection view is not working properly view on collection view taking size from storyboard design. its depend what you setting size in storyboard design. its working perfectly in Iphone but not working in Ipad. i tried to setting size in size for item at section but its not working.
dropbox link of project is here.
let isPad = UIDevice.current.userInterfaceIdiom == .pad
import UIKit
class AchivementVC: UIViewController {
#IBOutlet weak var clcAchivement:UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnBackClick(sender:UIButton)
{
self.navigationController?.popViewController(animated: true)
}
}
extension AchivementVC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "achiveCell", for: indexPath) as! AchiveClcCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
print(collectionView.frame)
if(isPad)
{
return CGSize(width: (collectionView.frame.size.width * 0.5)-30, height: (collectionView.frame.size.width * 0.45)-30)
}
else
{
return CGSize(width: (collectionView.frame.size.width * 0.5)-10, height: (collectionView.frame.size.width * 0.45)-10)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if(isPad)
{
return 30
}
else
{
return 10
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
if(isPad)
{
return 30
}
else
{
return 10
}
}
}
class AchiveClcCell:UICollectionViewCell
{
override func awakeFromNib() {
self.setNeedsLayout()
}
override func layoutSubviews() {
}
}
You should call super.layoutSubviews() when you override layoutSubviews

Changing size of selected UICollectionView Cell

I have a simple UICollectionViewController that returns X amount of cells. I want to have it so when a cell is selected, that specific selected cell will change it's size and become larger in height as all of the other cells stay the same. How do I achieve this? Here's my code:
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor(white: 0.90, alpha: 1.0)
collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.showsVerticalScrollIndicator = false
collectionView?.alwaysBounceVertical = true
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = (view.frame.width) * 9 / 16
return CGSize(width: view.frame.width, height: height + 50 + 50)
}
}
You can check to see if the indexPath from sizeForItemAt is selected. If it is, you return a different height otherwise return the standard height.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.performBatchUpdates(nil, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch collectionView.indexPathsForSelectedItems?.first {
case .some(indexPath):
return CGSize() // your selected height
default:
let height = (view.frame.width) * 9 / 16
return CGSize(width: view.frame.width, height: height + 50 + 50)
}
}

UICollectionViewLayout methods never get called

I am working with a UICollectionView and I am trying to use the UICollectionViewLayout methods to adjust the sizing of the cell however they are never being called. The methods are :
sizeForItemAtIndexPath, minimumInterimItemSpacingForSectionAtIndex, and minimumLineSpacingForSectionAtIndex
these 3 methods are never being called and I'm not sure where/ how to call them from. below is my code in Swift 3
import Foundation
import UIKit
class CollectionVC: UICollectionViewController {
var Sections = [SectionService]()
override func viewDidLoad() {
createServiceSections()
}
func createServiceSections(){
ServiceSections.append(ServiceSection(headerTitle: "1", items: 2, headerImage: UIImage(named: "Default"), stats: nil))
ServiceSections.append(ServiceSection(headerTitle: "2", items: 3, headerImage: UIImage(named: "Default"), stats: nil))
ServiceSections.append(ServiceSection(headerTitle: "3", items: 3, headerImage: UIImage(named: "Default"), stats: nil))
ServiceSections.append(ServiceSection(headerTitle: "4", items: 5, headerImage: UIImage(named: "Default"), stats: nil))
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return ServiceSections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ServiceSections[indexPath.section].items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "servicecell", for: indexPath) as! ServicesCellView
cell1.serviceLabel.text = "test"
cell1.serviceImage.image = ServiceSections[indexPath.section].headerImage
return cell1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
print("size for item at indexPath")
var cellSize: CGSize
let collectionViewWidth = self.collectionView!.bounds.size.width
cellSize = CGSize(width: (collectionViewWidth * 0.48), height: (collectionViewWidth * 0.48))
return cellSize
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInterItemSpacingForSectionAtIndex section: Int) -> CGFloat {
print("min spacing section")
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
print("min line spacing section")
return 1
}
}
With help from Xinatanil, I was able to fix the issue. First, I had to change my class line to this
class CollectionVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
and then I had to change the methods declarations to Swift 3 syntax...
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var cellSize: CGSize
let collectionViewWidth = self.collectionView!.bounds.size.width
cellSize = CGSize(width: (collectionViewWidth * 0.48), height: (collectionViewWidth * 0.48))
return cellSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
I think, you haven't set collectionView delegate
Please try:
self.collectionView.delegate = self in viewDidLoad() method
Actually UICollectionViewDelegateFlowLayout inherits from UICollectionViewDelegate. So setting the delegate will be sufficient.
Happy Coding!