I have a simple UICollectionViewController that is one section with a header and footer pinned to visible bounds. When I click a textField in the footer, the footer automatically animates above the keyboard and the collectionView scrolls to show the cells that otherwise would have been hidden by the keyboard as you would expect. However, when I click one outside of the keyboard, and dismiss it with a call to self.view.endEditing(true) the footer and collectionView do not react unless the collectionView is scrolled near the bottom. If the collectionView is scrolled near the bottom, the footer and collectionView animate as expected.
How can I force the footer and collectionView to animate properly every time?
In the images below, the header is orange, footer is green, and there are 10 cells that alternate red and blue.
Actual Behavior (occurs when you are not scrolled near the bottom of the collectionView when the keyboard dismisses)
Desired Behavior (occurs when you are scrolled at or near the bottom of the collectionView when the keyboard dismisses)
I know there are some methods to achieve this with Notifications when the keyboard appears and disappears but I would prefer to just use the default UICollectionViewController behavior if possible. Is there some configuration or setting I am missing?
Code:
New Single View App. Delete StoryBoard and ViewController.swift. Delete the main storyboard entry from the info plist file.
AppDelegate.swift
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = CollectionViewController.init()
return true
}
}
CollectionViewController.swift
import UIKit
private let reuseIdentifier = "Cell"
private let collectionViewHeaderFooterReuseIdentifier = "MyHeaderFooterClass"
class CollectionViewController: UICollectionViewController {
init() {
let collectionViewFlowLayout = UICollectionViewFlowLayout.init()
collectionViewFlowLayout.sectionHeadersPinToVisibleBounds = true
collectionViewFlowLayout.sectionFootersPinToVisibleBounds = true
super.init(collectionViewLayout: collectionViewFlowLayout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView?.register(MyHeaderFooterClass.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier)
self.collectionView?.register(MyHeaderFooterClass.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier)
self.collectionView?.backgroundColor = UIColor.white
self.collectionView?.dataSource = self
self.collectionView?.delegate = self
}
}
// MARK: UICollectionViewDelegate
extension CollectionViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
DispatchQueue.main.async {
self.view.endEditing(true)
self.collectionViewLayout.invalidateLayout()
self.collectionView?.layoutIfNeeded()
}
}
}
// MARK: - UICollectionViewDataSource
extension CollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
switch indexPath.row % 2 {
case 0:
cell.backgroundColor = UIColor.red
case 1:
cell.backgroundColor = UIColor.blue
default:
cell.backgroundColor = UIColor.gray
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier, for: indexPath)
if kind == UICollectionView.elementKindSectionHeader {
view.backgroundColor = UIColor.orange
}
else { //footer
view.backgroundColor = UIColor.green
}
return view
}
}
// MARK: - Collection View Flow Layout Delegate
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 100)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 100)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 100)
}
}
MyHeaderFooterClass
import UIKit
class MyHeaderFooterClass: UICollectionReusableView {
let textField: UITextField = {
let view = UITextField.init()
view.placeholder = "enter text here"
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(textField)
self.setNeedsUpdateConstraints()
}
override func updateConstraints() {
textFieldConstraints()
super.updateConstraints()
}
private func textFieldConstraints() {
NSLayoutConstraint(item: textField, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: textField, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: textField, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0.0).isActive = true
NSLayoutConstraint(item: textField, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
From documentation:
func layoutIfNeeded()
Use this method to force the view to update its layout immediately.
func invalidateLayout()
This method invalidates the layout of the collection view itself and
returns right away.
Solution:
Looking at your code, you are already updating collectionViewLayout. So, you don't need to force update collectionView again. Therefore, simply removing self.collectionView?.layoutIfNeeded() alone will solve your issue.
Change your code as below:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
DispatchQueue.main.async {
self.view.endEditing(true)
self.collectionViewLayout.invalidateLayout()
//self.collectionView?.layoutIfNeeded()
}
}
Related
I ran into a problem when using the simplest UICollectionView and UICollectionViewFlowLayout.
The collection itself works fine, but when the cell is removed, there are problems with the animation.
Here is a code example that demonstrates the problem:
class Cell: UICollectionViewCell { }
class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var items = Array(repeating: [UIColor.red, .blue, .yellow, .cyan, .magenta, .green], count: 100).flatMap { $0 }
lazy var collectionView: UICollectionView = {
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.scrollDirection = .vertical
collectionViewLayout.minimumLineSpacing = 10
collectionViewLayout.minimumInteritemSpacing = 10
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.register(Cell.self, forCellWithReuseIdentifier: "Cell")
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
NSLayoutConstraint.activate([
.init(item: collectionView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
.init(item: collectionView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
.init(item: collectionView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0),
.init(item: collectionView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
])
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.backgroundColor = items[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
CGSize(width: UIScreen.main.bounds.width, height: 300)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
items.remove(at: indexPath.item)
collectionView.deleteItems(at: [indexPath])
}
}
The problem itself looks like this (in slow motion):
You can notice how the next cell disappears for the duration of the animation, and at the end of it it appears.
Question: what am I doing wrong? This is a very basic use of a collection and I'm confused by these issues.
From the rest of the answers, the reason for this glitch became clear - there are problems with the deletion animation if some of the new cells are off the screen.
I solved the problem by adding layout invalidation to the animation block:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.performBatchUpdates({
self.items.remove(at: indexPath.item)
collectionView.deleteItems(at: [indexPath])
collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
It seems like there is a problem with your array.
It's created dynamically and has conflicts with UICollectionView's implementation.
Try replacing your array with the following static array.
var items = [UIColor.red, .blue, .yellow, .cyan, .magenta, .green, .red, .blue, .yellow, .cyan, .magenta, .green]
Here is what it looks like after changing it.
You have to subclass UICollectionViewFlowLayout and override these two methods
initialLayoutAttributesForAppearingItem
finalLayoutAttributesForDisappearingItem
by changing "attributes" properties you will get different effects just change the line 59 animation duration and check them out.
import UIKit
class Cell: UICollectionViewCell { }
class ViewController: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var items = Array(repeating: [UIColor.red, .blue, .yellow, .cyan, .magenta, .green], count: 100).flatMap { $0 }
lazy var collectionView: UICollectionView = {
let collectionViewLayout = MyCollectionLayout()
collectionViewLayout.scrollDirection = .vertical
collectionViewLayout.minimumLineSpacing = 10
collectionViewLayout.minimumInteritemSpacing = 10
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.register(Cell.self, forCellWithReuseIdentifier: "Cell")
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
NSLayoutConstraint.activate([
.init(item: collectionView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
.init(item: collectionView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
.init(item: collectionView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0),
.init(item: collectionView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
])
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.backgroundColor = items[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
CGSize(width: UIScreen.main.bounds.width, height: 300)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.2) {
self.collectionView.performBatchUpdates({
self.items.remove(at: indexPath.item)
collectionView.deleteItems(at: [indexPath])
}, completion: nil)
}
}
}
class MyCollectionLayout : UICollectionViewFlowLayout {
var rowOffset : CGFloat = 0.0
var deleteIndexPaths : Array<IndexPath> = []
var insertIndexPaths : Array<IndexPath> = []
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
super.prepare(forCollectionViewUpdates: updateItems)
self.deleteIndexPaths = Array<IndexPath>()
self.insertIndexPaths = Array<IndexPath>()
for updateItem in updateItems {
if (updateItem.updateAction == .delete){
self.deleteIndexPaths.append(updateItem.indexPathBeforeUpdate!)
}else if (updateItem.updateAction == .insert){
self.insertIndexPaths.append(updateItem.indexPathAfterUpdate!)
}
}
}
override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var attributes = super.initialLayoutAttributesForAppearingItem(at: itemIndexPath)
if(attributes == nil){
attributes = self.layoutAttributesForItem(at: itemIndexPath)
}
attributes?.alpha = 1
return attributes
}
override func finalizeCollectionViewUpdates()
{
super.finalizeCollectionViewUpdates()
self.deleteIndexPaths = [];
self.insertIndexPaths = [];
}
override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var attributes = super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath)
if ((attributes == nil)){
attributes = self.layoutAttributesForItem(at: itemIndexPath)
}
attributes?.transform = CGAffineTransform(scaleX: 0, y: 0)
attributes?.zIndex = -1
attributes?.alpha = 1
return attributes
}
}
I am currently working on a horizontal gallery scroll view. I have decided to use UICollectionView with horizontal paging enabled. It almost works great... expect on rotation the collection view cells are not centred (see screenshot attached), where red is the first cell and yellow is the second one.
It usually works fine on the first rotation but then just messes up :D
This is the code I have for setting up the class:
class GalleryScrollView: UIView {
private var collectionView: UICollectionView!
private var layout: UICollectionViewFlowLayout!
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
override func layoutSubviews() {
layout.invalidateLayout()
}
private func setupView() {
layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
collectionView = UICollectionView(frame: self.frame,
collectionViewLayout: layout)
collectionView.register(UINib(nibName: "PhotoGalleryCell", bundle: nil), forCellWithReuseIdentifier: "photoGalleryCell")
collectionView.isPagingEnabled = true
collectionView.contentInsetAdjustmentBehavior = .never
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = .flexibleWidth
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .green
self.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: self.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
collectionView.reloadData()
}
}
Followed by the collection view setup:
extension GalleryScrollView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoGalleryCell", for: indexPath) as? PhotoGalleryCell else {
return UICollectionViewCell()
}
if indexPath.item == 0 {
cell.backgroundColor = .red
} else {
cell.backgroundColor = .yellow
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
2
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.frame.size
}
I tried playing around with func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { but for some reason the func was never called.
Did anyone else run into this problem? I saw a lot of topics in objective c threads, not much in swift. I am also somewhat struggling to understand why this is happening, so just understanding the problem would be very helpful. Thank you!
You don't seem to have handled rotations. You need to reloadData when a rotation occurs. You'll get the event in UIViewController from there you can call reloadData on the instance of your UICollectionView.
class GalleryViewController: UIViewController {
//...
var galleryScrollView: GalleryScrollView
//...
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
galleryScrollView.collectionViewLayout.invalidateLayout()
}
//...
}
Then in GalleryScrollView:
class GalleryScrollView: UIView {
var currentVisibleIndexPath = IndexPath(row: 0, section: 0)
//....
}
extension GalleryScrollView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//...
func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
let attributes = collectionView.layoutAttributesForItem(at: currentVisibleIndexPath)
let newOriginForOldIndex = attributes?.frame.origin
return newOriginForOldIndex ?? proposedContentOffset
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let center = CGPoint(x: scrollView.contentOffset.x + (scrollView.frame.width / 2), y: (scrollView.frame.height / 2))
if let indexPath = self.screenView.indexPathForItem(at: center) {
currentVisibleIndexPath = indexPath
}
}
}
I have a custom collection view (tabBarCollectionView), which should load with the first cell being selected, as per the code below. However, this is not working. I know this as the cell should be a different colour when selected, but isn't.
override init(frame: CGRect) {
super.init(frame: frame)
tabBarCollectionView.register(TabBarCell.self, forCellWithReuseIdentifier: cellIdentifier)
addSubview(tabBarCollectionView)
tabBarCollectionView.translatesAutoresizingMaskIntoConstraints = false
addConstraintsWithFormat("H:|[v0]|", views: tabBarCollectionView)
addConstraintsWithFormat("V:|[v0]|", views: tabBarCollectionView)
tabBarCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [])
}
Full code of custom UIView class is inserted below:
import Foundation
import UIKit
class TabBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let cellIdentifier = "Cell"
let imageNames = ["homeIcon", "exploreIcon", "addIcon", "inboxIcon", "profileIcon"]
lazy var tabBarCollectionView: UICollectionView = {
// All collection view implementations in here
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.clear
return collectionView
}()
override init(frame: CGRect) {
super.init(frame: frame)
tabBarCollectionView.register(TabBarCell.self, forCellWithReuseIdentifier: cellIdentifier)
addSubview(tabBarCollectionView)
tabBarCollectionView.translatesAutoresizingMaskIntoConstraints = false
addConstraintsWithFormat("H:|[v0]|", views: tabBarCollectionView)
addConstraintsWithFormat("V:|[v0]|", views: tabBarCollectionView)
self.tabBarCollectionView.allowsSelection = true
self.tabBarCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [])
}
override func layoutSubviews() {
super.layoutSubviews()
tabBarCollectionView.allowsSelection = true
tabBarCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [])
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! TabBarCell
cell.backgroundColor = UIColor.clear
cell.tabBarImageView.image = UIImage(named: imageNames[indexPath.item])?.withRenderingMode(.alwaysTemplate)
cell.tabBarImageView.tintColor = UIColor.pinpointGrey
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: frame.width / 5, height: frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TabBarCell: UICollectionViewCell {
let tabBarImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "homeIcon")?.withRenderingMode(.alwaysTemplate)
imageView.tintColor = UIColor.pinpointGrey
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
backgroundColor = UIColor.clear
addSubview(tabBarImageView)
addConstraintsWithFormat("H:[v0(42)]", views: tabBarImageView)
addConstraintsWithFormat("V:[v0(42)]", views: tabBarImageView)
addConstraint(NSLayoutConstraint(item: tabBarImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: tabBarImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
override var isHighlighted: Bool {
didSet {
if tabBarImageView.isHighlighted == true {
self.tabBarImageView.tintColor = UIColor.pinpointBlue
} else {
self.tabBarImageView.tintColor = UIColor.pinpointGrey
}
}
}
override var isSelected: Bool {
didSet {
tabBarImageView.tintColor = isSelected ? UIColor.pinpointBlue : UIColor.pinpointGrey
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Where is your datasource set? Do you load it separately and then do a reloadData()?
If yes, then you should select the cell then and not during your viewDidLoad method as during load the collection view might not have been populated yet.
You could also add to a viewWillAppear/viewDidAppear method as this gets called after the collection view has been populated
I'm developing an application without storyboards/xibs, which is proving to be a challenge. I have a UICollectionView (of ads) where users can tap on a cell to navigate to a new view controller to show details for that ad. Below is a gif of the error I'm having.
As you can see, the UICollectionView kind of sticks around after I tap the cell. I have a adDetailsViewController property in my AdsViewController subclass, and when I tap the cell this code executes:
adDetailsViewController.adTitle = adTitles[indexPath.row]
navigationController?.pushViewController(adDetailsViewController, animated: true)
Below are the life cycle methods (currently just viewDidLoad) of adDetailsViewController:
class AdDetailsViewController: UIViewController {
var adTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: view.bounds)
label.textAlignment = .center
label.center = view.center
label.text = adTitle
view.addSubview(label)
}
}
For completeness, here's the rest of AdsViewController:
class AdsViewController: UIViewController {
lazy var collectionView: AdsCollectionView = {
let collectionView = AdsCollectionView(frame: view.frame, collectionViewLayout: TiledFlowLayout())
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(AdCollectionViewCell.self, forCellWithReuseIdentifier: "AdCell")
view.addSubview(collectionView)
return collectionView
}()
let adDetailsViewController = AdDetailsViewController()
let adTitles = ["1", "2", "3", "4", "5", "6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 8).isActive = true
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
view.backgroundColor = .white
}
}
extension AdsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return adTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AdCell", for: indexPath) as! AdCollectionViewCell
cell.textLabel.text = adTitles[indexPath.row]
return cell
}
}
extension AdsViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
adDetailsViewController.adTitle = adTitles[indexPath.row]
navigationController?.pushViewController(adDetailsViewController, animated: true)
}
}
extension AdsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (self.view.frame.size.width / 2) - 10, height: self.view.frame.size.height / 4)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
}
Ok, I fixed it. It seems that if I set the backgroundColor of AdDetailsViewController to UIColor.white, then it transitions as expected.
You have to share more of your code. Are there any special settings f.e.? Like a transparent background? Anything you do in viewDidLoad? Did you overwrite viewWillAppear, viewDidAppear, etc. and did not call the subclass functions (like super.viewWillAppear(animated))? That's a very common mistake...
In Xcode 8.2.1 and Swift 3 I have a UICollectionView inside a UITableViewCell but I can't get the layout right. basically I want to be able to see all of the star. I can adjust the size of the star but I want to fix the underlying problem, expanding the blue band.
Here is a shot of the view The red band is contentView and the blue band is collectionView. At first glance it looks like collectionView height is the problem but it is actually being hidden by something else. I can't find or change whatever it is hiding the collectionView cell.
I am not using the storyboard beyond a view controller embedded in a navigator.
Here's all the relevant code.
class WishListsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView()
let tableCellId = "WishListsCell"
let collectionCellId = "WishListsCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .white
tableView.register(WishListsCell.self, forCellReuseIdentifier: tableCellId)
self.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
func numberOfSections(in tableView: UITableView) -> Int {
return wishLists.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: tableCellId, for: indexPath) as! WishListsCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView,willDisplay cell: UITableViewCell,forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? WishListsCell else { return }
//here setting the uitableview cell contains collectionview delgate conform to viewcontroller
tableViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forSection: indexPath.section)
tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
}
func tableView(_ tableView: UITableView,didEndDisplaying cell: UITableViewCell,forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? WishListsCell else { return }
storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
}
}
extension WishListsViewController: UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellId, for: indexPath) as! WishListsCollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
}
class WishListsCell: UITableViewCell {
private var collectionView: UICollectionView!
let cellId = "WishListsCollectionViewCell"
var collectionViewOffset: CGFloat {
get { return collectionView.contentOffset.x }
set { collectionView.contentOffset.x = newValue }
}
func setCollectionViewDataSourceDelegate<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(dataSourceDelegate: D, forSection section : Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = section
collectionView.reloadData()
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: contentView.frame, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .blue
collectionView.register(WishListsCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
contentView.backgroundColor = .red
self.contentView.addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class WishListsCollectionViewCell: UICollectionViewCell {
var imageView: UIImageView
override init(frame: CGRect) {
imageView = UIImageView()
super.init(frame: frame)
contentView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
contentView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = .white
NSLayoutConstraint.activate([
NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal,
toItem: contentView, attribute: .width,
multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal,
toItem: contentView, attribute: .height,
multiplier: 1.0, constant: 0.0),
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
You can Use View Debugging
Run the project, go back to Xcode and click on the Debug View Hierarchy button in the Debug bar. Alternatively, go to Debug\View Debugging\Capture View Hierarchy.
Now you can select your red view and Xcode will indicate which view is selected.
For more info. Check out: View Debugging in Xcode
Specifically, the problem was the collection view frame had not been properly set. This was only revealed by the great tip that I didn't know about in the accepted answer.
This fixed it:
self.collectionView.frame = CGRect(0, 0, screenWidth, (screenWidth / 4) * Constants.IMAGE_ASPECT_RATIO)