Duplicate Objects in PFQueryCollectionViewController - swift

I am fairly new to Swift and Parse and am attempting to use PFQueryCollectionViewController to load a set of images and titles. The problem is that my PFQueryCollectionViewCell is duplicating the same image and text label in the simulator although I have multiple objects within the class name I am querying. I have searched multiple discussion threads, but can't seem to find a solution that solves it. It's probably something super simple that I am overlooking but my eyes are starting to bleed!
Thanks in advance for your help.
FeedViewController (PFQueryCollectionViewController)
import Foundation
import UIKit
import Parse
import ParseUI
import Bolts
let reuseIdentifier:String = "feedCell"
class FeedViewController: PFQueryCollectionViewController, UICollectionViewDelegateFlowLayout {
let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Configure the PFQueryCollectionView
self.parseClassName = "Products"
self.pullToRefreshEnabled = true
self.paginationEnabled = true
self.objectsPerPage = 50
}
override func queryForCollection() -> PFQuery {
var query = PFQuery(className: "Products")
query.orderByAscending("createdAt")
return query
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> PFCollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as? FeedViewCell
let item = indexPath.item
for object in objects {
cell?.parseObject = object[item] as? PFObject
if let parseObject = object["url"] as? String? {
cell?.productImage?.image = nil
if var urlString: String? = parseObject as String? {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!) {
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.productImage?.image = UIImage(data: imageData) } )}
} }
cell?.title?.text = object["title"] as? String
var text = object["title"] as? String
}
return cell!
}
override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath ) {
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath)
}
override func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 170, height: 300)
}
override func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInsets
}
}
FeedViewCell (PFQueryCollectionViewCell)
import Foundation
import UIKit
import Parse
import ParseUI
class FeedViewCell: PFCollectionViewCell {
#IBOutlet weak var productImage: PFImageView?
#IBOutlet weak var title: UILabel?
var parseObject:PFObject?
}

Related

Swift - How to enable and generate horizontal scroll of UICollection View that is within a UITableViewCell?

I have a UICollectionView placed inside a UITableViewCell. The collection view has its scroll direction set to horizontal. However, when I swipe left or right on it to try and scroll, it doesn't work. Instead the table view cell is just pressed. It seems like the table view is eating up the gesture and not allowing the collection view to register it.
How can I make it so the collection view can scroll left and right with horizontal swipes, while still allowing the parent table view to scroll vertically?
Image that I want to the first cell to have a collection view of images horizontally and on the other cells rows of names for example .
you can see my project on this GitHub account : https://github.com/BenSeferidis/Nft-Assets/tree/version4 for better understanding .
the code is the following :
LobbyViewController (Main VC):
import UIKit
class LobbyViewController: UIViewController {
// MARK: - IBProperties
#IBOutlet weak var tableView: UITableView!
// MARK: - Properties
var data: [DataEnum] = []
var likes:[Int] = []
var numlikes: Int = 0
var nfts: [Nft] = []
let creators : [Creator] = []
var icons: [Icon] = []
var loadData = APICaller()
// MARK: - Life Cyrcle
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "AssetTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "AssetTableViewCell")
let nib2 = UINib(nibName: "CreatorsTableViewCell", bundle: nil)
tableView.register(nib2, forCellReuseIdentifier: "CreatorsTableViewCell")
tableView.dataSource = self //method to generate cells,header and footer before they are displaying
tableView.delegate = self //method to provide information about these cells, header and footer ....
downloadJSON {
self.tableView.reloadData()
print("success")
}
loadData.downloadData { (result) in
print(result)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? PresentViewController {
destination.nft = nfts[tableView.indexPathForSelectedRow!.row]
destination.delegate = self
}
}
// MARK: - Methods
func downloadJSON(completed: #escaping () -> ()) {
let url = URL(string: "https://public.arx.net/~chris2/nfts.json")
URLSession.shared.dataTask(with: url!) { [self] data, response, error in
if error == nil {
do {
self.nfts = try JSONDecoder().decode([Nft].self, from: data!)
nfts.forEach { nft in
let creators = nfts.map (\.creator)
self.data.append(.type1(creators: creators))
}
self.nfts.forEach { nft in
self.data.append(.type2(nft: nft))
}
DispatchQueue.main.async {
completed()
}
}
catch {
print("error fetching data from api")
}
}
}.resume()
}
}
// MARK: - Extensions
extension LobbyViewController : UITableViewDelegate , UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
indexPath.row == 0 ? 100 : UITableView.automaticDimension
}
//gemizo ta rows tou table
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch self.data[indexPath.item] {
case .type1(let creators):
let cell = tableView.dequeueReusableCell(withIdentifier: "CreatorsTableViewCell",
for: indexPath) as! CreatorsTableViewCell
//cell.creatorsCollectionView = self
return cell
case .type2(let nft):
let cell = tableView.dequeueReusableCell(withIdentifier: "AssetTableViewCell",
for: indexPath) as! AssetTableViewCell
cell.nameLabel?.text = nft.name
cell.nameLabel.layer.cornerRadius = cell.nameLabel.frame.height/2
cell.likesLabel?.text = "\((numlikes))"
let imgUrl = (nft.image_url)
print(imgUrl)
cell.iconView.downloaded(from: imgUrl)
cell.iconView.layer.cornerRadius = cell.iconView.frame.height/2
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetails", sender: self)
}
}
extension LobbyViewController : TestDelegate{
func sendBackTheLikess(int: Int) {
numlikes = int
tableView.reloadData()
}
}
// MARK: - Enums
enum DataEnum {
case type1(creators: [Creator])
case type2(nft: Nft)
}
// MARK: - Struct
struct Constants {
static let url = "https://public.arx.net/~chris2/nfts.json"
}
Creators TableViewCell :
import UIKit
class CreatorsTableViewCell: UITableViewCell {
//MARK: - IBProtperties
#IBOutlet var creatorsCollectionView: UICollectionView!
#IBOutlet var creatorsLbl: UILabel!
//MARK: - Properties
var nft : Nft?
var creators : [Creator] = []
var users: User?
weak var delegate : CreatorsTableViewCellDelegate?
//MARK: - Life Cyrcle
override func awakeFromNib() {
super.awakeFromNib()
creatorsCollectionView.dataSource = self
creatorsCollectionView.delegate = self
let nibName = UINib(nibName: "CollectionViewCell", bundle: nil)
creatorsCollectionView.register(nibName, forCellWithReuseIdentifier: "CollectionViewCell")
creatorsCollectionView.horizontalScrollIndicatorInsets
}
//init
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: 10 , height: 10)
layout.sectionInset = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
super.init(style: style, reuseIdentifier: reuseIdentifier)
creatorsCollectionView.showsHorizontalScrollIndicator = true
creatorsCollectionView.showsVerticalScrollIndicator = false
}
required init?(coder aDecoder : NSCoder) {
super.init(coder: aDecoder)
}
func setUpCollection(creators: Creator) {
creatorsLbl.text = creators.user.username
}
}
//MARK: - Extensions
extension CreatorsTableViewCell : UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return creators.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = creatorsCollectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell",
for: indexPath) as! CollectionViewCell
// cell.setUpCollectionViewCell((nft?.creator.profileImgURL[indexPath.row])!)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated:true)
}
}
//MARK: - Protocols
protocol CreatorsTableViewCellDelegate: AnyObject {
func didSelectPhoto(index: Int)
}
CollectionViewController :
import UIKit
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController , UICollectionViewDelegateFlowLayout {
let creatorsCellId = "creatorsCellId"
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
// self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
func setupCollectionView() {
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.backgroundColor = .lightGray
let nib = UINib(nibName: "CollectionViewCell", bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: creatorsCellId)
collectionView?.register(CollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
}
}
}
extension CollectionViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: creatorsCellId, for: indexPath) as! CollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 180, height: view.frame.height-60)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
}
CollcetionViewCell:
import UIKit
class CollectionViewCell: UICollectionViewCell {
//MARK: - IBProperties
#IBOutlet var creatorsImg: UIImageView!{
didSet {
creatorsImg.contentMode = .scaleAspectFit
}
}
//MARK: - Properties
var nft : Nft?
//MARK: - Life Cyrcle
override func awakeFromNib() {
super.awakeFromNib()
}
func setUpCollectionViewCell(_ nft: Nft) {
let imgUrl = (nft.creator.profileImgURL)
print(imgUrl)
creatorsImg.downloaded(from: imgUrl)
// creatorsImg.image = UIImage(named: (nft.creator.profileImgURL))
creatorsImg.layoutIfNeeded()
creatorsImg.layer.cornerRadius = creatorsImg.frame.height / 2
}
}
the results is this :

How can I update a UICollectionView from another class?

I am trying this for a couple of days now and haven't achieved anything yet. What I am trying to do is when a user picks a User item form the ViewController class, I want to save it in Realm and show it in the CollectionView of the SavedInterestsViewController class. I use a delegate pattern as suggested in this post How to access and refresh a UITableView from another class in Swift, but unfortunately I still receive nil, I guess because the GC removed the collectionView outlet already right? (please correct me if I misunderstood it). However, how can I get this to work by using a delegate pattern? Here is my code, this is the class where the user Picks a new User-item:
protocol ViewControllerDelegate {
func didUpdate(sender: ViewController)
}
class ViewController: UIViewController {
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var collectionView: UICollectionView!
var delegate: ViewControllerDelegate?
let numberOfTweets = 5
let realm = try! Realm()
var image = UIImage()
var imageArray: [String] = []
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
searchBar.delegate = self
}
}
extension ViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("One second...")
let functionClass = NetworkingFunctions()
var loopCount = 0
functionClass.getWikipediaAssumptions(for: searchBar.text!) { [self] (articleArray) in
self.userArray.removeAll()
for x in articleArray {
functionClass.performWikipediaSearch(with: x, language: WikipediaLanguage("en")) { (user) in
self.userArray.append(user)
collectionView.reloadData()
loopCount += 1
}
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if userArray[indexPath.item].checked == false {
userArray[indexPath.item].checked = true
collectionView.reloadData()
let newUser = User()
newUser.image = userArray[indexPath.item].image
newUser.name = userArray[indexPath.item].name
newUser.checked = true
try! realm.write {
realm.add(newUser)
}
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
}
else {
userArray[indexPath.item].checked = false
collectionView.reloadData()
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
class User: Object {
#objc dynamic var image: NSData = NSData()
#objc dynamic var name: String = ""
#objc dynamic var checked: Bool = false
}
... and this is the class where I want to show the selected item, after the User clicked on the 'Back' Button of the navigation controller of the ViewController class:
class SavedInterestsViewController: UIViewController, ViewControllerDelegate {
func didUpdate(sender: ViewController) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var collectionView: UICollectionView!
let realm = try! Realm()
var userArray: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCell")
fetchDataFromRealm()
}
#IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "SavedToNew", sender: self)
}
func fetchDataFromRealm() {
userArray.append(contentsOf: realm.objects(User.self))
collectionView.reloadData()
}
}
extension SavedInterestsViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionViewCell
let image = UIImage.init(data: userArray[indexPath.item].image as Data)
cell.userImage.image = image
cell.nameLabel.text = userArray[indexPath.item].name
cell.userImage.layer.borderColor = image?.averageColor?.cgColor
if userArray[indexPath.item].checked == false {
cell.checkmark.isHidden = true
} else {
cell.checkmark.isHidden = false
}
return cell
}
}
extension SavedInterestsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width/3 - 10
let height = width
return CGSize(width: width, height: height)
}
}
in your code you have lines
self.delegate = SavedInterestsViewController()
self.delegate?.didUpdate(sender: self)
but it do mostly nothing - you set the delegate to newly created class, didUpdate it - but I don't see any use of it - you don't present it in any way.
If I understand you right - you have SavedInterestsViewController, from it - you open ViewController, do something and when back to SavedInterestsViewController. (I can be wrong with your flow - correct me if so)
In this flow - you have delegate property in ViewController, but it must be of type SavedInterestsViewController. And you have to set it to SavedInterestsViewController when you open ViewController from it. And later in ViewController you have to call didUpdate method of delegate.

How to retrieve the images from firebase storage according to the category of the images as wanted

How to Retrieve the images from firebase storage in which I have manually created folders according the category of my "wallpaper app" and I have created a list of "items" according to the category of my wallpaper. I am not understanding how to retrieve the images according to the "items"-(it is there in the code below) from the storage of firebase and display it accordingly.
I just want to store all the images according to the category of the "items" which is specified in the code below and display it in the app.
import UIKit
import GlidingCollection
import FirebaseStorage
import Firebase
class ViewController: UIViewController {
#IBOutlet var glidingView: GlidingCollection!
fileprivate var collectionView: UICollectionView!
fileprivate var items = ["riches", "animals", "nature", "architecture","toys"]
fileprivate var images: [[UIImage?]] = []
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
setupGlidingCollectionView()
loadImages()
}
func setupGlidingCollectionView() {
glidingView.dataSource = self
let nib = UINib(nibName: "CollectionCell", bundle: nil)
collectionView = glidingView.collectionView
collectionView.register(nib, forCellWithReuseIdentifier: "Cell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = glidingView.backgroundColor
}
func loadImages() {
let storage = Storage.storage()
let storageRef = storage.reference()
let starsRef = storageRef.child("Animals")
starsRef.downloadURL { url, error in
if let error = error {
print("not there")
} else {
for item in self.items {
let imageURLs = FileManager.default.fileUrls(for: "jpeg", fileName: item)
var images: [UIImage?] = []
for url in imageURLs {
guard let data = try? Data(contentsOf: url) else { continue }
let image = UIImage(data: data)
images.append(image)
}
self.images.append(images)
}
}
}
}
}
// MARK: - Setup
// MARK: - CollectionView 🎛
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? CollectionCell else { return UICollectionViewCell() }
let section = glidingView.expandedItemIndex
let image = images[section][indexPath.row]
cell.imageView.image = image
cell.contentView.clipsToBounds = true
let layer = cell.layer
let config = GlidingConfig.shared
layer.shadowOffset = config.cardShadowOffset
layer.shadowColor = config.cardShadowColor.cgColor
layer.shadowOpacity = config.cardShadowOpacity
layer.shadowRadius = config.cardShadowRadius
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let section = glidingView.expandedItemIndex
let item = indexPath.item
print("Selected item #\(item) in section #\(section)")
}
}
// MARK: - Gliding Collection 🎢
extension ViewController: GlidingCollectionDatasource {
func numberOfItems(in collection: GlidingCollection) -> Int {
return items.count
}
func glidingCollection(_ collection: GlidingCollection, itemAtIndex index: Int) -> String {
return "– " + items[index]
}
}
in another swift file linked to the cell of the collection view."CollectionCell.xib"
import UIKit
class CollectionCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
}
I want all the images categorised and according to the items displayed in my app.

how to make flip animation in UICollectionViewCell with array of images swift 4

I'm trying to implement flip animation in UICollectionViewCell. I have done it with 2 types of images. But I don't know how to implement it in array of images. The logic now:
but I want logic like this:
this is my code:
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var coImage: UIImageView!
let cardBackTag = 0
let cardFrontTag = 1
var cardViews: (frontView: UIImageView, backView: UIImageView)?
var imgViewFront: UIImageView!
var imgViewBack: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
imgViewFront = self.createCardWithImage(imageName: "1", tag: self.cardFrontTag)
imgViewBack = self.createCardWithImage(imageName: "2", tag: self.cardBackTag)
cardViews = (frontView: imgViewFront, backView: imgViewBack)
contentView.addSubview(imgViewBack)
}
private func createCardWithImage(imageName: String, tag: Int) -> UIImageView {
let newCardImageView = UIImageView(frame: self.frame)
newCardImageView.image = UIImage(named: imageName)
newCardImageView.tag = tag
return newCardImageView
}
func flipCardAnimation(indexPath: IndexPath) {
if (imgViewBack.superview != nil) {
cardViews = (frontView: imgViewFront, backView: imgViewBack)
}else{
cardViews = (frontView: imgViewBack, backView: imgViewFront)
}
let transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft
UIView.transition(with: self.contentView, duration: 1.0, options: transitionOptions, animations: {
self.cardViews!.backView.removeFromSuperview()
self.contentView.addSubview(self.cardViews!.frontView)
}, completion: { finished in
print(indexPath)
})
}
}
and
import UIKit
class CollectionViewController: UICollectionViewController {
var reuseIdentifier = "CollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
cell.flipCardAnimation(indexPath: indexPath)
}
}
Please, help me to implement this logic! Thank you a lot!!

display images on collectionview inside tableview

I'm trying to display images on collectionview inside tableview.
I implemented codes like so
//Model
import UIKit
import Firebase
struct Post {
var key: String
var Date: String
var tweetImageUrl = [URL]()
var Text: String
init(snapshot: DataSnapshot) {
self.key = snapshot.key
self.Date = (snapshot.value as! NSDictionary)["Date"] as? String ?? ""
self.Text = (snapshot.value as! NSDictionary)["Text"] as? String ?? ""
if let urls = (snapshot.value as! NSDictionary)["tweetImageUrl"] as? [String:String] {
for (_,value) in urls {
if let finalUrl = URL(string: value) {
tweetImageUrl.append(finalUrl)
}
}
}
}
}
//tableviewcell
import UIKit
class TimellineTableViewCell: UITableViewCell {
#IBOutlet var profileImage: UIImageView!
#IBOutlet var tempoName: UILabel!
#IBOutlet var dateLabel: UILabel!
#IBOutlet var caption: UILabel!
#IBOutlet var collectionView: UICollectionView!
var post: Post? {
didSet {
tempoName.text = "channing"
dateLabel.text = post?.Date
caption.text = post?.Text
profileImage.image = #imageLiteral(resourceName: "heart")
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
profileImage.layer.cornerRadius = 30.0
profileImage.layer.masksToBounds = true
}
}//class
extension TimellineTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let count = post?.tweetImageUrl.count else { return 0 }
return count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeLineCell", for: indexPath) as! TimelineCollectionViewCell
cell.configCell(post: post)
return cell
}
}//extension
//collectionviewcell
import UIKit
class TimelineCollectionViewCell: UICollectionViewCell {
#IBOutlet var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
func configCell(post: Post?) {
guard let imageUrl = post?.tweetImageUrl else { return }
for url in imageUrl {
URLSession.shared.dataTask(with: url, completionHandler: { (data, res, err) in
guard let data = data else { return }
let image = UIImage(data: data)
DispatchQueue.main.async {
self.imageView.image = image
}
}).resume()
}
}
}//class
//viewcontroller
import UIKit
import Firebase
class TimelineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var TimelinetableView: UITableView!
var ref: DatabaseReference! {
return Database.database().reference()
}
let uid = Auth.auth().currentUser?.uid
var tweets = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
self.TimelinetableView.rowHeight = UITableViewAutomaticDimension
self.TimelinetableView.estimatedRowHeight = 300
fetchTweets()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TimelinetableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TimellineTableViewCell
cell.post = tweets[indexPath.row]
return cell
}
func fetchTweets() {
ref.child("TWEETS").child(uid!).observe(.value, with: { (snapshot) in
var result = [Post]()
for post in snapshot.children {
let post = Post(snapshot: post as! DataSnapshot)
result.append(post)
}
self.tweets = result.sorted(by: { (p1, p2) -> Bool in
p1.Date > p2.Date
})
self.TimelinetableView.reloadData()
}, withCancel: nil)
}//func
}//class
But if I run it simulator looks like this
If I selected one of these cell, components come out except imageview on the collectionview. If cell is not being selected, simulator looks like a cell which says "Really fun". Does anyone have any idea how to fix this?
It's about constrains not the code. So, after I gave constrains properly it worked fine.