UICollectionView appears black when running the App - swift

I am using swift 2.0 and xcode 7. I would like to have a vertical collection view with an array of image on my app. However when I run my project the UICollectionView area appears black. I have set the script on my ViewController but I don't what I'm missing. I already have set an identifier and all other stuff. Could somebody help me please. Thanks.
ViewController Script
ViewController error message

I guess you forgot about delegates, it's typical error.
Also, try use this example of code
class ExampleCollectionView: UIViewController, UICollectionViewDelegate
{
#IBOutlet weak var collectionView: UICollectionView!
let tshirtsArray = ["tshirt_1.png",
"tshirt_2.png",
"tshirt_3.png",
"tshirt_4.png"]
override func viewDidLoad()
{
super.viewDidLoad()
collectionView.delegate = self
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return self.tshirtsArray.count
}
func collectionView(cv: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell: UICollectionViewCell = cv.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath)
let collectionImageView: UIImageView = cell.viewWithTag(100) as! UIImageView
collectionImageView.image = UIImage(named: self. tshirtsArray[indexPath.row])
return cell
}
}

I've made the UICollectionView display the images although i still need to update the sizes. I've followed #pdobsk advice to look through the error message and it says that i should consider the cell size together with the margin and other stuffs because the cell size is the same size with the collection view.
error fixed!

Related

XCode Simulator black screen

I Just start learning UIKit, i got a problem when trying to run the program, my simulator is going well, but simulator only shows black screen, without any problem on terminal, is there someone recognize my fault?
here is my PageViewController and screenshot blackscreen
import UIKit
class OnboardingViewController: UIPageViewController {
#IBOutlet weak var pageControllView: UIPageControl!
#IBOutlet weak var collectionView: UICollectionView!
var onboardingPage: [OnboardingModel] = []
override func viewDidLoad() {
super.viewDidLoad()
onboardingPage = [
OnboardingModel(description: "Welcome to Future Box", image: #imageLiteral(resourceName: "treasure")),
OnboardingModel(description: "Future Box will save your thoughts about about something and save it on your local data, you can set time for that", image: #imageLiteral(resourceName: "Idea")),
OnboardingModel(description: "And when you set the time for your thoughts, Future Box will remind you again when the time is up", image: #imageLiteral(resourceName: "clock"))
]
}
}
extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return onboardingPage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
cell.setupPage(page: onboardingPage[indexPath.row])
return cell
}
}
There are some possible reasons:
You set wrong Project -> Deployment Info -> Main Interface
Main Storyboard Base Name is wrong
Entry Point in the storyboard is not set
Not set:
collectionView.delegate = self
collectionView.dataSource = self
Usage of
class OnboardingViewController: UIPageViewController {}
instead of
class OnboardingViewController: UIViewController {}
You can check your view hierarchy from the visual debugger to see what is on device's screen.

Segue from selected collection view cell sends to wrong collection view

I am using swift. I'm trying to create a collectionView segue to lead to a new viewController.
I have a series of (lets say 8) different images and labels as an array within the collectionView, and the when selected, I want the user to be sent to another view controller (with 8 different possibilities - one for each cell). I have been able to get the app to build, but the behaviour from selecting a cell is wrong.
The first cell that is selected has no response, then the next cell initiates a segue - but to the previously selected one! Each time a different cell is selected, it segues to the previous selected cell. Can anyone help me correct this error?
I have used performSegue and pushViewController separately, following different tutorials on youtube, but each resolves to the same issue.
The various view controllers to segue to have been allocated their own storyboardID in the main.storyboard file. The initial view controller is embedded within a navigation controller, and each new veiwcontroller (to segue to) has been connected to the collection view of the main view controller.
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet var CollectionView: UICollectionView!
// created an array for labels
let NamesForSectionTitles = ["Overview","Canopy trees","Mid-story trees","Understory plants","Birds","Mammals","Ferns","Butterflys"]
// created list of images to be loaded in the collectionview
let sectionIconImages: [UIImage] = [
UIImage(named: "IMG_8750_landscape_night")!,
UIImage(named: "IMG_8789_Trees")!,
UIImage(named: "IMG_2185_Tree_Olearia")!,
UIImage(named: "_MG_9528_Herb_Flower")!,
UIImage(named: "IMG_3654-")!,
UIImage(named: "IMG_9892-2")!,
UIImage(named: "IMG_9496_Ferns_crozier")!,
UIImage(named: "IMG_7707_Butterfly")!,
]
override func viewDidLoad() {
super.viewDidLoad()
// load the data sources and delegate
CollectionView.dataSource = self
CollectionView.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return NamesForSectionTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ->
UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.SectionTitle.text = NamesForSectionTitles[indexPath.row]
cell.sectionImages.image = sectionIconImages[indexPath.row]
return cell
}
// tells the collection view that upon selecting a cell, show the next UIView controller, as suggested in storyboard name (main.storyboard property) - tutoral from https://www.youtube.com/watch?v=pwZCksvXGRw&list=PLPUDRZDcNNsMdyfZVw4CJDT1Wu8cYx_6E&index=7&t=0s
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: NamesForSectionTitles[indexPath.row], sender: self)
}
}
The viewer should see an image view with a label, that when selected takes them to a new collection view.
Can't Comment so posting an answer
I think
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) is causing the issue.
Please try changing that line to:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

UICollectionViewCell not shown properly

I have the following code. For some strange reason, the cell is not registering properly and the cell is not rendered.
I expect there to be 5 purple cells but instead there is only red background.
class RateController: UICollectionViewController {
var user: User?
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .red
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = .purple
return cell
}
}
There's nothing wrong with your code. I pasted it right into a fresh project, defined the User class, made the necessary adjustments in the storyboard, and ran it:
So if there's a problem, it's somewhere else — not in that code!
I've been thinking about where else the problem could be; the problem you are describing would happen if you disabled the Flow layout in the storyboard and replaced it with an empty Custom layout, like this:
If you did that, set the Layout back to Flow.

Assign image to cell in CollectionViewController

I am using Xcode 9.2 and Swift 4.0
I have a UICollectionViewController that Xcode has generated for me. I have customized it a bit and my code sort of looks like this.
class CollectionViewController: UICollectionViewController {
var images = [UIImage(named: “image1“), [UIImage(named: “image2“), [UIImage(named: “image3“)]
//stuff deleted
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
code
}
}
I had expected there to be an image property on the cell below, so this is the Swift I thought I would be writing.
class CollectionViewController: UICollectionViewController {
var images = [UIImage(named: “image1“), [UIImage(named: “image2“), [UIImage(named: “image3“)]
//stuff deleted
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
cell.image = images[indexPath.row] //this doesn’t compile
}
}
The code does not compile.
Yes I have tried to solve this myself but most examples on the web, including here on StackOverflow, seem to show something very similar to what I want yet does compile.
Thank you.
By default UICollectionViewCell doesn't have image property. You need to cast it to your type if it have such property or create UIImageView with given image and add it to the cell.

UICollectionViewCell's subview absolute frame

Have been having this issue that I considered to be an easy solve, but spent a lot of time cracking it with no result.
So, I have a UIViewController with UICollectionView in it. This collection is padded 75 px from the top and has cells with pretty simple setup - just 1 UIImageView set to fit the size of the container. Everything is made with AutoLayout.
My task is to make UIImageView go full screen on tap. What I am doing is making a temporary UIImageView and add to the hierarchy of UIViewController view.
The problem I am facing is I can't get the absolute frame of UIImageView in the cell I tap.
I tried various ways to calculate the frame, my most recent try is
var rect = cell.imageView.superview!.convertRect(cell.imageView.frame, toView: self.view)
However, it returns result that seems to be ignoring the collection view top constraint.
Update:
It turns out my problem was in the wrong way I was acquiring the cell from collection view. Instead of:
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! UIImageCollectionViewCell
I was getting cell with
let cell = self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! UIImageCollectionViewCell
Which obviously resulted in creating a new cell with the wrong frame. My bad, late night coding is not the best thing sometimes. Thanks to Arun Ammannaya for the quick example
This what i tried, works as expected.
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCellWithReuseIdentifier("aaa", forIndexPath: indexPath)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 10
}
#IBAction func frame(sender: AnyObject) {
print(String(sender.frame))
let rect = sender.superview??.convertRect(sender.frame, toView: self.view)
print(String(rect))
let addedView = UIView()
view.addSubview(addedView)
addedView.frame = rect!
addedView.backgroundColor = UIColor.yellowColor()
}
}
Story board looks like:
Output is looks like: