Assign image to cell in CollectionViewController - swift

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.

Related

UICollectionViewCell is not rounding corners inside UITableView

The problem is that when I have UICollectionView inside UITableViewCell - UICollectionViewCell cornerRadius function not working.
Code is very simple and it was always working for me when playing with UICollectionView.
extension ExploreTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ExploreCollectionViewCell
cell.thumbnail.layer.cornerRadius = 20
cell.thumbnail.clipsToBounds = true
return cell
}
Is it a bug or what? Cannot find any answer all day. Most of the people suggest to use contentView instead of the specific image inside the cell but that's not for me since I want only image to be rounded.
P.S this one works (but I want only image inside the cell to be rounded):
override func awakeFromNib() {
super.awakeFromNib()
self.layer.cornerRadius = 30
self.clipsToBounds = true
}

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)

passing image from collectionViewCell which is located tableviewCell

I ask for help with determining the right approach
when I click on the picture I need to pass text and her to new VC, but the problem is that the project has a great depth struct
the cell lies in the collectionView, which is in the tableViewCell
How do I properly implement the transfer?
(the number of cells is generated automatically)
Another complication is that the code of the cell with which I work lies in another cell.
those. the transfer of information must also be written in it.
import UIKit
import moa
class RealPhotoInfoTableViewCell: UITableViewCell {
#IBOutlet private weak var MyCollection: UICollectionView!
var model: RealPhoto!
func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
MyCollection.delegate = self
MyCollection.dataSource = self
MyCollection.reloadData()
}
}
extension RealPhotoInfoTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(model?.data.count as Any)
return model?.data.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RPhotoCell", for: indexPath) as! RealPhotoCollectionViewCell
cell.realPhotoImage.moa.url = model?.data[indexPath.row].photo
return cell
}
}
Add a var
class RealPhotoInfoTableViewCell: UITableViewCell {
weak var delegate:VCName?
Inside cellForRowAt of the table do
cell.delegate = self
Now you can do this inside didSelectItemAt of the collection
delegate?.sendData(image)
You have two options:
One is Sh_Khan answer using delegation.
Or you can use Notification observers.
This question has been asked before...
You can use delegate protocol in that case. You can implement that protocol. Please find following sample code for that.
protocol ImageSelectionDelegate {
func imageClicked(imageURL: String)
}
//Class A
class A : ImageSelectionDelegate{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//your existing code
cell.delegate = self
}
//Implement that protocol
func imageClicked(imageURL: String){
//You will get url for tapped image
}
}
class RealPhotoInfoTableViewCell{
weak var delegate : ImageSelectionDelegate? = nil
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate.imageClicked(model?.data[indexPath.item].photo)
}
}

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.

UICollectionView appears black when running the App

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!