First I had a couple of UIButtons with a #IBAction to play a sound when tapped. Because I had some problems with constraints on different iPhones I decided to go for a UICollectionView with CustomCells. Now I got this working I want to setup the CustomCells to play a sound when tapped. So I think I will have to setup something like an 'Action' on the custom cells for playing a sound. I do have a 'sort of action' that prints out that the user tapped a custom cell like;
print("tapped tag > ", self.tag)
The original #IBAction I used on a UIButton was:
#IBAction func sound2(_ sender: UIButton) {
sound2.play()
Again, I 'think' I need to setup a sort of action to the CustomCell for playing a sound?
And I 'think' I need to declare somewhere what sound to play along with the self.tag?
So each customCell will play a different sound..
The only problem, (rookieAlert) I don't know where to start :(
But I want to learn!
Can somebody point me into the right direction or provide me with some information?
Here is the full code of the project to make things more clear:
import UIKit
import AVFoundation
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var countries = [UIImage(named:"c1"),UIImage(named:"c2"),UIImage(named:"c3"),UIImage(named:"c4"),UIImage(named:"c5"),UIImage(named:"c6"),UIImage(named:"c7"),UIImage(named:"c8"),UIImage(named:"c9"),UIImage(named:"c10")]
#IBOutlet weak var soundsCollectionView: UICollectionView!
lazy var cv: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 100, height: 100)
var cc = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
cc.translatesAutoresizingMaskIntoConstraints = false
cc.register(CustomCell.self, forCellWithReuseIdentifier: "CustomCell")
cc.delegate = self
cc.dataSource = self
cc.backgroundColor = .black
return cc
}()
let sounds = ["sound1", "sound2", "sound3", "sound4", "sound5"]
var sound1 = AVAudioPlayer()
var sound2 = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(cv)
cv.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
cv.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
cv.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
cv.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
// Setting up sound1
do {
sound1 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sound1", ofType: "mp3")!))
sound1.prepareToPlay()
} catch {
print(error)
}
// Setting up sound2
do {
sound2 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sound2", ofType: "mp3")!))
sound2.prepareToPlay()
} catch {
print(error)
}
}
#IBAction func sound2(_ sender: UIButton) {
if sound2.isPlaying {
sound2.stop()
sound1.stop()
sender.setImage(UIImage(named: "sound1_off.jpg"), for: .normal)
} else {
sound2.play()
sender.setImage(UIImage(named: "sound1_on.jpg"), for: .normal)
}
}
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 = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.centerImageView.image = countries[indexPath.row]
cell.tag = indexPath.row
cell.backgroundColor = UIColor.green
return cell
}
//define constant value as per your requirement and declare this variables globally
let inset: CGFloat = 10 //define as per your requirement
let minimumInteritemSpacing: CGFloat = 10 //define as per your requirement
let cellsPerRow = 3
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let marginsAndInsets = inset * 2 + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return .init(width: itemWidth, height: itemWidth)
}
}
class CustomCell: UICollectionViewCell {
lazy var centerImageView: UIImageView = {
var img = UIImageView()
img.translatesAutoresizingMaskIntoConstraints = false
img.clipsToBounds = true
img.isUserInteractionEnabled = true
img.contentMode = .scaleAspectFill
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handler(_:)))
tapGesture.numberOfTapsRequired = 1
img.addGestureRecognizer(tapGesture)
return img
}()
#objc private func handler(_ sender: UITapGestureRecognizer) {
print("tapped tag > ", self.tag)
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(centerImageView)
centerImageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
centerImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
centerImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
centerImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
This is for same sound in all cell: try to delete gesture from your centerImage in custom cell, after that add the gesture in cellForItemAt and call the function like this:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.centerImageView.image = countries[indexPath.row]
cell.backgroundColor = UIColor.green
let gesture = UITapGestureRecognizer(target: self, action: #selector(playCellSound))
cell.centerImageView.addGestureRecognizer(gesture)
return cell
}
after that write the func below cellForItemAt:
#objc func playCellSound() {
sound2.play()
print("play sound...")
}
FOR DIFFERENT SOUND IN CELLS:
the number of sounds must be equal the number of countries:
let sounds = ["sound1", "sound2", "sound3", "sound4", "sound5", "sound6", "sound7", "sound8", "sound9", "sound10"]
after that declare your sounds like this:
var sound1 = AVAudioPlayer()
var sound2 = AVAudioPlayer()
var sound3 = AVAudioPlayer()
var sound4 = AVAudioPlayer()
var sound5 = AVAudioPlayer()
var sound6 = AVAudioPlayer()
var sound7 = AVAudioPlayer()
var sound8 = AVAudioPlayer()
var sound9 = AVAudioPlayer()
var sound10 = AVAudioPlayer()
set the other sound like sound 1 and sound 2
now this is your cellForItemAt:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.centerImageView.image = countries[indexPath.row]
cell.backgroundColor = UIColor.green
return cell
}
set numberOfItemsInSection like this:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return countries.count // dynamic number of items based on your countries array
}
implement the method didiSelectItemAt
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let s = sounds[indexPath.item]
switch s {
case "sound1":
sound1.play()
print("s1")
case "sound2":
sound2.play()
print("s2")
case "sound3":
sound3.play()
print("s3")
case "sound4":
sound4.play()
print("s4")
case "sound5":
sound5.play()
print("s5")
case "sound6":
sound6.play()
print("s6")
case "sound7":
sound7.play()
print("s7")
case "sound8":
sound8.play()
print("s8")
case "sound9":
sound9.play()
print("s9")
case "sound10":
sound10.play()
print("s10")
default:
break
}
}
in your custom cell delete tap gesture for centerImageView:
class CustomCell: UICollectionViewCell {
lazy var centerImageView: UIImageView = {
var img = UIImageView()
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.isUserInteractionEnabled = true
img.translatesAutoresizingMaskIntoConstraints = false
return img
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(centerImageView)
centerImageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
centerImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
centerImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
centerImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
FOR SYSTEM SOUNDS:
replace your var declaration like this:
var sound1: SystemSoundID = 1016
var sound2: SystemSoundID = 1322
var sound3: SystemSoundID = 1110
var sound4: SystemSoundID = 1070
var sound5: SystemSoundID = 1109
var sound6: SystemSoundID = 1117
var sound7: SystemSoundID = 1106
var sound8: SystemSoundID = 1118
var sound9: SystemSoundID = 1256
var sound10: SystemSoundID = 1116
deleting setting up sound 1, 2 etc. and replace the switch case in didSelectItemAt with this:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let s = sounds[indexPath.item]
switch s {
case "sound1":
AudioServicesPlaySystemSound (sound1)
print("s1")
case "sound2":
AudioServicesPlaySystemSound(sound2)
print("s2")
case "sound3":
AudioServicesPlaySystemSound(sound3)
print("s3")
case "sound4":
AudioServicesPlaySystemSound(sound4)
print("s4")
case "sound5":
AudioServicesPlaySystemSound(sound5)
print("s5")
case "sound6":
AudioServicesPlaySystemSound(sound6)
print("s6")
case "sound7":
AudioServicesPlaySystemSound(sound7)
print("s7")
case "sound8":
AudioServicesPlaySystemSound(sound8)
print("s8")
case "sound9":
AudioServicesPlaySystemSound(sound9)
print("s9")
case "sound10":
AudioServicesPlaySystemSound(sound10)
print("s10")
default:
break
}
}
}
this is not the best way but it work fine, it will make you understand how it works and help you to learn
I believe what you are looking for is implementation of the didSelectItemAt function. You can implement like so by putting with your other collection view functions like cellForItemAt. Then, make sure the required sound is closely linked with your data source. Meaning you can access the sound you want via indexPath.item, which is a way of identifying the specific cell that got tapped.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Use indexPath.item to determine what sound to play
}
Related
I had everything working perfectly in test.
In production, a user saved a few images, two are ok but for some reason, two are doubling up on top of another image.
When tapping on the image (didSelectItemAt)
collectionView.reloadData()
Gets called and each tap, changes the image to clear it up into just one image.
I've worked back from this point but I'm stuck.
Images loaded in viewDidLoad
db.collection("SAVED IMAGE IDS").getDocuments()
{
(querySnapshot, err) in
if let err = err
{
print("Error getting documents: \(err)")
}
else
{
for document in querySnapshot!.documents
{
let id = document.documentID
let Ref = Storage.storage().reference(forURL: "SavedUserImages/\(id)")
Ref.getData(maxSize: 1 * 1024 * 1024)
{
data, error in
if error != nil
{
print("Error: Image could not download!")
}
else
{
let image = UIImage(data: data!)
self.picArray.append(image!)
self.imageID.append(id)
self.collectionView.reloadData()
}
}
}
}
}
Image loads in cell for row
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath as IndexPath)
let data = picArray[indexPath.row]
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
let iv = UIImageView()
cell.contentView.addSubview(iv)
iv.frame = cell.contentView.frame
iv.image = data
collectionView.selectItem(at: IndexPath(item: 0, section: 0) as IndexPath, animated: false, scrollPosition: .init())
return cell
}
Thanks in advance for any help
With this code:
you are adding another image view every time you reload the cell.
Instead, you need to design your cell to already have the image view and change your code to:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath as IndexPath)
let data = picArray[indexPath.row]
cell.iv.image = data
return cell
}
Edit - further explanation and examples...
Based on the code you've shown, you are using a default UICollectionViewCell instead of a custom subclassed cell.
So, if we do a complete example, using SF Symbol images from 0 to 14 for the picArray, using your approach:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let cellID: String = "cell"
var collectionView: UICollectionView!
var cvWidth: CGFloat = 0
// let's use an array of images for this example
var picArray: [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
// create images 0 through 14
for i in 0..<15 {
if let img = UIImage(systemName: "\(i).circle") {
picArray.append(img)
}
}
let fl = UICollectionViewFlowLayout()
fl.scrollDirection = .vertical
collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: g.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
collectionView.dataSource = self
collectionView.delegate = self
// it appears you're using a default collection view cell class
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// only do this is the collection view frame has changed
if cvWidth != collectionView.frame.width {
cvWidth = collectionView.frame.width
if let fl = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
fl.itemSize = CGSize(width: cvWidth, height: 200.0)
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath as IndexPath)
let data = picArray[indexPath.row]
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
// this is wrong... we're Adding ANOTHER image view every time
let iv = UIImageView()
cell.contentView.addSubview(iv)
iv.frame = cell.contentView.frame
iv.image = data
// this makes no sense, but I'll leave it here
collectionView.selectItem(at: IndexPath(item: 0, section: 0) as IndexPath, animated: false, scrollPosition: .init())
return cell
}
}
It looks like this at the start:
if we scroll all the way down - to where the "14" image should be the bottom cell, it looks like this:
If we scroll back to the top:
and after scrolling up and down several times:
As we can see, as the cells are reused we keep adding more and more image views on top of each other.
So, instead, let's create a simple custom cell subclass that creates and adds an image view when it is created:
class SimpleImageCell: UICollectionViewCell {
let imgView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
imgView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imgView)
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
imgView.topAnchor.constraint(equalTo: g.topAnchor),
imgView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
imgView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
imgView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
}
}
and we'll use an almost identical view controller - the only differences are registering our SimpleImageCell class, and using a correct cellForItemAt func:
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let cellID: String = "cell"
var collectionView: UICollectionView!
var cvWidth: CGFloat = 0
// let's use an array of images for this example
var picArray: [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
// create images 0 through 14
for i in 0..<15 {
if let img = UIImage(systemName: "\(i).circle") {
picArray.append(img)
}
}
let fl = UICollectionViewFlowLayout()
fl.scrollDirection = .vertical
collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: g.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
collectionView.dataSource = self
collectionView.delegate = self
// register cell class that already has an image view
collectionView.register(SimpleImageCell.self, forCellWithReuseIdentifier: cellID)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// only do this is the collection view frame has changed
if cvWidth != collectionView.frame.width {
cvWidth = collectionView.frame.width
if let fl = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
fl.itemSize = CGSize(width: cvWidth, height: 200.0)
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! SimpleImageCell
let data = picArray[indexPath.item]
cell.imgView.image = data
return cell
}
}
The results:
We can scroll up and down all we want, and we will never have images "on top of" each other.
I have a problem when pull-to-refresh with UICollectionView. The refreshing control work well but when I click on a cell, push another view controller, and pop back, try refreshing, UICollectionView is disappeared( I don't use storyboard).
Screen record video:
https://www.youtube.com/watch?v=3bsaqqv6x_8
Here is my code:
AccountController
class AccountController: UICollectionViewController, UICollectionViewDelegateFlowLayout{
var menuData: [Any]? {
didSet{
self.collectionView?.reloadData()
}
}
let collectionLayout = UICollectionViewFlowLayout()
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
...
setupCollectionView()
self.collectionView?.isHidden = false
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
collectionView!.addSubview(refreshControl)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
super.collectionViewLayout.invalidateLayout()
}
func setupCollectionView(){
self.collectionView?.isHidden = true
collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
collectionView?.alwaysBounceVertical = true
collectionView?.register(MenuCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(MenuSupplementary.self, forCellWithReuseIdentifier: supplementaryId)
collectionLayout.minimumLineSpacing = 0
collectionView?.collectionViewLayout = collectionLayout
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = menuData?.count {
return count
}
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let dt = menuData?[indexPath.item] {
if dt is MenuCellData{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MenuCell
cell.data = dt as? MenuCellData
return cell
}
if dt is MenuSupplementaryData {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: supplementaryId, for: indexPath) as! MenuSupplementary
cell.data = dt as? MenuSupplementaryData
return cell
}
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: view.frame.width, height: 45)
}
#objc func refresh(sender:UIRefreshControl){
let api = AccountApi(jwt: appDelegate.userDefault.string(forKey: "jwt"))
api.getMenuData { (data) in
var dt: [Any] = []
if data.isEmpty { return }
for d in data as! [MenuData] {
if d.type == "supplementary" {
dt.append(MenuSupplementaryData( d.text ))
}
if d.type == "cell" {
dt.append(MenuCellData(d.icon!, d.text, isTheLastItem: d.isTheLastItem ?? false, url: d.url, httpMethod: d.httpMethod ))
}
}
if !dt.isEmpty {
self.menuData = dt
}
sender.endRefreshing()
}
}
}
TabBarController
class TabBarController: UITabBarController, UITabBarControllerDelegate {
...
private func setUpNavControllerFrom(viewController: UIViewController, title: String, imageName: String)-> UINavigationController{
let navController = UINavigationController(rootViewController: viewController)
navController.tabBarItem.title = title
navController.tabBarItem.image = UIImage(named: imageName)
let imageView = UIImageView.init(frame: CGRect())
imageView.image = UIImage(named: "logo")
imageView.contentMode = .scaleAspectFit
imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true // Set logo height
viewController.navigationItem.titleView = imageView
navController.navigationBar.barTintColor = themeColor
return navController
}
// Set up color, logo, font ...
private func setupViewControllers(){
tabBar.tintColor = UIColor.white
tabBar.barTintColor = themeColor
let accountVC = AccountController(collectionViewLayout: UICollectionViewFlowLayout())
let accNavController = setUpNavControllerFrom(viewController: accountVC, title: "Account", imageName: "account-icon")
...
}
}
Additional info:
Refreshing without pop back: numberOfItemsInSection, cellForItemAt, sizeForItemAt of delegate is invoked when call collectionView?.reloadData().
But, when refreshing after pop back, cellForItemAt, sizeForItemAt of delegate is not invoked when call collectionView?.reloadData().
Thanks for help!
Thanks for trying help me!
I finally find out my mistake.
When handling menu is selected, I create new controller with current collectionViewLayout, and I think this current layout is changed when pop back, make menu is disappeared.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let dt = menuData?[indexPath.item]{
if dt is MenuCellData {
let d = dt as! MenuCellData
// let controller = AccountMenuController(collectionViewLayout: collectionView.collectionViewLayout)
let controller = AccountMenuController(collectionViewLayout: UICollectionViewLayout())
controller.menuData = d
navigationController?.pushViewController(controller, animated: true)
}
}
}
I'm making an iPhone app using Firebase and I'm having a small issue with the following code.
import UIKit
import Firebase
class ChatController: UICollectionViewController, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {
var game: Game? {
didSet {
navigationItem.title = game?.name
}
}
lazy var inputTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Enter message..."
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.alwaysBounceVertical = true
collectionView?.backgroundColor = UIColor.white
collectionView?.register(ChatMessageCell.self, forCellWithReuseIdentifier: cellId)
setupInputComponents()
}
var messages = [Message]()
func observeMessages() {
let ref = Database.database().reference().child("games").child((game?.id)!).child("messages")
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let message = Message()
message.setValuesForKeys(dictionary)
self.messages.append(message)
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
}, withCancel: nil)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! ChatMessageCell
// let message = messages[indexPath.item]
// cell.textView.text = message.text
cell.backgroundColor = UIColor.blue
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: NSIndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 80)
}
// Sets up the entire message sending
// container for the send button and input
// text field
func setupInputComponents() {
// Creates the container for send button
// and input text field
let containerView = UIView()
containerView.backgroundColor = UIColor.white
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
// anchor constraints and x,y,w,h
// for positioning the container
containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
// Creates the send button
let sendButton = UIButton(type: .system)
sendButton.setTitle("Send", for: .normal)
sendButton.translatesAutoresizingMaskIntoConstraints = false
sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
containerView.addSubview(sendButton)
// Positions the send button within the container
sendButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
sendButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
sendButton.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
// Creates the input text field
containerView.addSubview(inputTextField)
// Positions the send button within the container
inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true
inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
// Create a seperator for this component
let seperatorLineView = UIView()
seperatorLineView.backgroundColor = UIColor(r: 220, g: 220, b: 220)
seperatorLineView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(seperatorLineView)
// Positions the seperator
seperatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
seperatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
seperatorLineView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
seperatorLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
#objc func handleSend() {
let ref = Database.database().reference().child("games").child("-L6lIJt_cw6saNNWMgu1").child("messages")
ref.keepSynced(true)
let childRef = ref.childByAutoId()
let values = ["text": inputTextField.text!]
childRef.updateChildValues(values)
}
}
I have some commented out pieces which are actually what I'm wanting to display as text in my cells but I can't even get the colored boxes to show up for me inside the CollectionViewController. The DB retrieval code works perfectly fine and I can display what it gives me in a TableViewController. It's just not in the CollectionViewController that I've made here.
What is happening exactly is that the application builds and loads successfully, but when I navigate to this screen, the cells that I am creating aren't showing up. Those lines specifically are the following:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
// return 5
}
override func collectionView(_ collectionView: UICollectionView,, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! ChatMessageCell
// let message = messages[indexPath.item]
// cell.textView.text = message.text
cell.backgroundColor = UIColor.blue
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: NSIndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 80)
}
You need to add the following delegates and data source.
To your class add UICollectionViewDataSource and UICollectionViewDelegate.
Then in your viewDidLoad add self.collectionView?.delegate = selfand self.collectionView?.dataSource = self.
This tells the view controller that it’s delegate and data source methods are in its own class.
This should solve your issue. Sorry if the formatting is off a bit in this answer. On my phone so can’t see the question as I type the answer!
I want a variable in my code that keeps track of the index of my UICollectionView, but I can't get it to work. After some troubleshooting, I've boiled down the code to the following, which if pasted into an empty viewController should work since no storyboard is involved. The animated gif illustrates the problem. Initially my variable "selectedItem" is equal to the UICollectionView Cell text which reflects the data = [0,1,2,3], but then when I swipe right, it immediately becomes off by 1. Then it stays off by 1 until at the last cell where it matches again. The pattern repeats when going in reverse. Thanks for any help --
import UIKit
class CodeCollView2: UIViewController, UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var data = [0,1,2,3] //["0", "1", "2", "3" ]
let cellId = "cellId2"
var selectedItem = 0
lazy var cView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.isPagingEnabled = true
cv.dataSource = self
cv.delegate = self
return cv
}()
var indexLabel: UILabel = {
let label = UILabel()
label.text = ""
label.font = UIFont.systemFont(ofSize: 30)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
func setupViews() {
cView.register(CCell2.self, forCellWithReuseIdentifier: cellId)
view.addSubview(cView)
cView.translatesAutoresizingMaskIntoConstraints = false
cView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
cView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
cView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
cView.heightAnchor.constraint(equalToConstant: 200).isActive = true
view.addSubview(indexLabel)
indexLabel.translatesAutoresizingMaskIntoConstraints = false
indexLabel.bottomAnchor.constraint(equalTo: cView.topAnchor).isActive = true
indexLabel.centerXAnchor.constraint(equalTo: cView.centerXAnchor).isActive = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CCell2
selectedItem = indexPath.item
indexLabel.text = "seletedItem = \(selectedItem)"
cell.itemValue = data[selectedItem]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.frame.size
}
}
//============== CVCell ==================
class CCell2: UICollectionViewCell {
var itemValue: Int? {
didSet {
if let val = itemValue {
itemLabel.text = "\(val)"
}
}
}
var itemLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 100)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .lightGray
addSubview(itemLabel)
itemLabel.translatesAutoresizingMaskIntoConstraints = false
itemLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
itemLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
As Nikita's answer mentions, cellForItemAt is called when a cell is going to be shown, even if you only see a bit of it and go back to the previous one, so you shouldn't use to decided what cell is at the centre.
scrollViewDidScroll is the right way of tracking which cell you have at the centre, and you can print what index you are on with something like this:
func scrollViewDidScroll(_ scrollView:UIScrollView)
{
let midX:CGFloat = scrollView.bounds.midX
let midY:CGFloat = scrollView.bounds.midY
let point:CGPoint = CGPoint(x:midX, y:midY)
guard
let indexPath:IndexPath = collectionView.indexPathForItem(at:point)
else
{
return
}
let currentPage:Int = indexPath.item
indexLabel.text = "seletedItem = \(currentPage)"
}
Tracking the selected item in the 'cellForItemAt' is not a good idea. I would suggest you to track it in the scrollViewDidScroll delegate method of the UIScrollViewDelegate.
Something like this should work:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentPage = cView.contentOffset.x / self.view.bounds.width
}
I have a tableViewCell with a collectionView, collectionView's cells are custom ones, they contains just a imageView.
Here is my test project
Here are DataSource required methods from my CollectionView class:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
let image = UIImage(named: listItems[indexPath.row])
cell.testImageView.image = image
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listItems.count
}
When I try to set image for cell's imageView I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I have checked image, it isn't nil, but testImageView is, I get this error when I try to set image to collectionViewCell's testImageView.
How can I fix it?
EDIT1
Here is method called from tableViewController to fill collectionView's listItem
func load(listItem: [String]) {
self.listItems = listItem
reloadData()
}
Also if I remove code from collectionView cellForItemAt indexPath with this one all is working fine
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath)
let imageView = UIImageView(image:UIImage(named: listItems[indexPath.row]))
cell.backgroundView = imageView
You have mistaken your two view controllers. Your IB outlet is connected to a cell in a different view controller. I mean you can have multiple views in different controllers connected to a same IBOutlet, but in your case the one that loads first is not connected, so that is why it crashes.
This is the cell your outlet was connected to.
This is that you are trying to load (but did not connect IBOutlet to image view):
Just in case you want to use code instead..
import UIKit
class ImageCell : UICollectionViewCell {
private var imageView: UIImageView!
private var descLabel: UILabel!
public var image: UIImage? {
get {
return self.imageView.image
}
set {
self.imageView.image = newValue
}
}
public var imageDesc: String? {
get {
return self.descLabel.text
}
set {
self.descLabel.text = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initControls()
self.setTheme()
self.doLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initControls()
self.setTheme()
self.doLayout()
}
override func awakeFromNib() {
super.awakeFromNib()
}
func initControls() {
self.imageView = UIImageView()
self.descLabel = UILabel()
}
func setTheme() {
self.imageView.contentMode = .scaleAspectFit
self.descLabel.numberOfLines = 1
self.descLabel.lineBreakMode = .byWordWrapping
self.descLabel.textAlignment = .center
self.descLabel.textColor = UIColor.black
self.contentView.backgroundColor = UIColor.white
}
func doLayout() {
self.contentView.addSubview(self.imageView)
self.contentView.addSubview(self.descLabel)
self.imageView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5).isActive = true
self.imageView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5).isActive = true
self.imageView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0).isActive = true
self.descLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5).isActive = true
self.descLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5).isActive = true
self.descLabel.topAnchor.constraint(equalTo: self.imageView.bottomAnchor, constant: 5).isActive = true
self.descLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -5).isActive = true
for view in self.contentView.subviews {
view.translatesAutoresizingMaskIntoConstraints = false
}
}
}
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private var collectionView: UICollectionView!
private var dataSource: Array<String>!
override func viewDidLoad() {
super.viewDidLoad()
self.initDataSource()
self.initControls()
self.setTheme()
self.registerClasses()
self.doLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func initDataSource() {
self.dataSource = ["Image1", "Image2", "Image3", "Image4", "Image5", "Image6"]
}
func initControls() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 117, height: 125)
layout.invalidateLayout()
self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
func setTheme() {
self.collectionView.backgroundColor = UIColor.clear
self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
self.view.backgroundColor = UIColor.blue
}
func registerClasses() {
self.collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "ImageCellIdentifier")
}
func doLayout() {
self.view.addSubview(self.collectionView)
self.collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
for view in self.view.subviews {
view.translatesAutoresizingMaskIntoConstraints = false
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCellIdentifier", for: indexPath) as! ImageCell
let imageName = self.dataSource[indexPath.row]
cell.image = UIImage(named: imageName)
cell.imageDesc = imageName
return cell
}
}
http://imgur.com/o7O7Plw
maybe the "testImageView" outlet variable is not connected from the interface builder or there is no CollectionViewCell with reuseIdentifier "ImageCell". Check whether cell is nil or not using LLDB po command.