Pass data from CollectionviewCell to ViewController - swift

when i write the function touchphoto, the post.postID is nil .I want to pass the postID to another view controller. I add the code for the profilecell and profileviewcontroller
protocol profilecellDelegate {
func goToPhotoDetail(postid: String)}
class profilecell: UICollectionViewCell {
var delegate: profilecellDelegate?
#IBOutlet weak var image: UIImageView!
var post: Post? {
didSet {
updateView()
}
}
func updateView() {
if let photoUrlString = post?.photoUrl {
let photoUrl = URL(string: photoUrlString)
image.sd_setImage(with: photoUrl)
}
}
#IBAction func touchphoto(_ sender: Any) {
if let id = post?.postID {
delegate?.goToPhotoDetail(postid: id)
}
}
}
//profileviewcontroller
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "profilecell", for: indexPath) as! profilecell
let post = posts[indexPath.row]
cell.post = post
cell.delegate = self
return cell
}
extension ProfileViewController: profilecellDelegate {
func goToPhotoDetail(postid: String) {
performSegue(withIdentifier: "Photo_ProfileSegue", sender: postid)
}}

Related

In my view collection I added a search bar and it filtered the cells but when I click the cell it it self it the path didn't change

In my view collection I added a search bar and it filtered the cells but when I click the cell it self the path didn't change the path remain the same as it was before the search .
When I click the cell, it should take you to a specific page. Excuse my poor code but I just started to learn swift. And my problem might be super easy and obvious so bare with me please
This is my code I'm using swift storyboard
import UIKit
import Firebase
import FirebaseStorage
class resViewViewController: UIViewController, UISearchBarDelegate, UISearchDisplayDelegate
{
#IBOutlet weak var background: UIImageView!
#IBOutlet weak var icon: UIImageView!
#IBOutlet weak var resL: UILabel!
#IBOutlet weak var collection: UICollectionView!
var resources:[resFile] = []
let db = Firestore.firestore()
//dummy data
#IBOutlet weak var searchBar: UISearchBar!
var searchActive : Bool = false
var filtered:[resFile] = []
override func viewDidLoad() {
super.viewDidLoad()
let nipCell = UINib(nibName: "resourceCellCollectionViewCell", bundle: nil)
//
collection.delegate = self
collection.dataSource = self
searchBar.delegate = self
///
collection.register(nipCell, forCellWithReuseIdentifier: "cell")
loadResources()
}
func loadResources(){
db.collection("Resources").getDocuments { querySnapshot, error in
if let e = error {
print("There was an issue retrieving data from fireStore. \(e)")
}else {
if let snapshotDocuments = querySnapshot?.documents{
for doc in snapshotDocuments{
let data = doc.data()
if let rName = data["ResName"] as? String, let aName = data["authorName"] as? String, let pName = data["pubName"] as? String, let desc = data["desc"] as? String, let urlName = data["url"] as? String {
let newRes = resFile(name: rName, author: aName, publisher: pName, desc: desc, urlString: urlName)
self.resources.append(newRes)
DispatchQueue.main.async {
self.collection.reloadData()
}
}
}
// DispatchQueue.main.async {
// self.collection.reloadData()
// }
}
}
}
}//end loadResources
//search
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchActive = false;
self.searchBar.endEditing(true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
self.searchBar.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchActive = false;
self.searchBar.endEditing(true)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filtered = resources.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.collection.reloadData()
}
}//end of class
extension resViewViewController:UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = (UIScreen.main.bounds.size.width - 110)/2
return CGSize(width: w, height: 160) //154
}//end size
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(searchActive) {
return filtered.count
} else {
return resources.count
}
}//end count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! resourceCellCollectionViewCell
if(searchActive) {
cell.name.text = filtered[indexPath.row].name
} else {
cell.name.text = resources[indexPath.row].name
}
return cell
}//end cell
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "si_resourceListToDetail", sender: indexPath)
}//end
}//extention
extension resViewViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "si_viewResToPost", let vc = segue.destination as? resPostViewController {
vc.delegate = self
} else if segue.identifier == "si_resourceListToDetail",
let vc = segue.destination as? detailedResViewController, let indexPath = sender as? IndexPath {
vc.resource = resources[indexPath.row]
}
}
}//extension
extension resViewViewController: resPostViewControllerDelegate {
func resPost(_ vc: resPostViewController, resource: resFile?, added: Bool){
vc.dismiss(animated: true) {
if added, let r = resource {
self.resources.append(r)
self.collection.reloadData()
}
}
}
}//extension
The indexPath will always be the same if you select the first visible cell in the UICollectionView. You must check the underlying data set to get the difference..
Also: In Swift it's convention to have capital first letter of classes and structs.
You must do something like this to achieve what you want:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item: ResFile
if searchActive {
item = filtered[indexPath.item]
} else {
item = resources[indexPath.item]
}
performSegue(withIdentifier: "si_resourceListToDetail", sender: item)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let item = sender as? ResFile else { return }
// Send item to destination view controller
}

Swift 4 Switch relate to label on tableView

I have problem to get label from cell when i turn my switch ON. I do fetch all labels from Firebase Database.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tagCell", for: indexPath) as! TagsTableViewCell
print(myCallList[indexPath.row])
let _tag = myCallList[indexPath.row]
cell.tagLabel?.text = _tag.type
return cell
}
UPDATED:
UITableViewCell contain nothing special
import UIKit
class TagsTableViewCell: UITableViewCell {
#IBOutlet weak var tagLabel: UILabel!
#IBOutlet weak var tagSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
My model:
class Calls: NSObject {
var type: String?
init(type: String?) {
self.type = type
}
}
LoadCalls contain Firebase data fetch:
func LoadCalls() {
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
self.myCallList.removeAll()
ref.child("tags").observe(.childAdded, with: { (snapshot) in
if snapshot != nil{
var tagType = snapshot.key as? String
let myCalls = Calls(type: tagType)
self.myCallList.append(myCalls)
print(self.myCallList.count)
DispatchQueue.main.async {
self.tagsTableView.reloadData()
}
}
})
}
A delegate / protocol for communication between cell and table controller can work well here.
protocol switchCellDelegate : Class {
func cellSwitchChanged( value: String, sender: Any)
}
update table view cell with property and IBAction for switch change
class TagsTableViewCell: UITableViewCell {
weak var delegate : switchCellDelegate?
#IBAction func switchChanged(sender: UISwitch){
guard let delegate = delegate else { return }
if sender.isOn {
delegate.cellSwitchChanged( value: tagLabel.text, sender: self)
}
}
and then in cellForRowAtIndex, add this
cell.delegate = self
and controller
extension myController : switchCellDelegate {
func cellSwitchChanged( value: String, sender: Any){
//do what you want here
}
}
I guess it something like this - add tag to switcher and create action for it
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tagCell", for: indexPath) as! TagsTableViewCell
print(myCallList[indexPath.row])
let _tag = myCallList[indexPath.row]
cell.tagLabel?.text = _tag.type
cell.switcher.tag = indexPath.row
return cell
}
And after this
#IBAction func switcherChanged(_ sender: UISwitch) {
var getLabel = myCallList[(sender as AnyObject).tag]
print(getLabel.type)
}

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.

Collectionviewcell only showing in one of the tab item

I have my storyboard set up such that
Tab bar controller -> nav bar controller 1, nav bar controller 2 -> CollectionView controller 1, CollectionView controller 2
The content inside my collectionviews are basically database i get from firebase (which is working fine). It's just when I start up my app, I can't see the cells in the first collectionview but I can see the cells in my second collectionview. Also, I added a print statement and a segue when you click on a cell and this actually works on both collectionviews. I just can't see the content (just a label) of my collectionviewcell in the first collectionview (the first tab item).
This is the code for my first tab bar item
import Foundation
import UIKit
import Firebase
class SaleListViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let rootref = FIRDatabase.database().reference()
let storage = FIRStorage.storage()
var item_names = [String]()
var item_image_urls = [String]()
var item_details = [Dictionary<String, String>]()
var group = DispatchGroup()
var processRunning = false
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.load_data()
}
/**
Call the firebase function
*/
func load_data(){
self.group.enter()
self.processRunning = true
get_firebase_data(){
if(self.processRunning){
self.processRunning = false
self.group.leave()
}
}
self.group.notify(queue: DispatchQueue.main, execute: {
print("done")
})
}
/**
Get data from firebase database
- parameter completionHandler: Function to be called once it's finished
*/
func get_firebase_data(completionHandler: () -> ()){
rootref.child("Sale").observe(.value, with: { (snapshot) in
if(snapshot.exists()){
var item_data = snapshot.value! as! Dictionary<String, AnyObject>
for(type_2_container,item_list) in item_data{
for(uid_container, item_detail_container) in item_list as! Dictionary<String, AnyObject>{
for(uid, item_detail) in item_detail_container as! Dictionary<String, AnyObject>{
var item_detail_dict = item_detail as? Dictionary<String,String>
var item_detail_temp = Dictionary<String, String>()
for key in (item_detail_dict?.keys)!{
item_detail_temp[key] = item_detail_dict?[key]
}
item_detail_temp["user_id"] = uid
self.item_details.append(item_detail_temp)
if(!self.item_names.contains(item_detail_dict!["item_name"]!)){
self.item_names.append(item_detail_dict!["item_name"]!)
self.item_image_urls.append(item_detail_dict!["item_image"]!)
}
}
}
}
print(self.item_details)
self.collectionView?.reloadData()
print("data was reloaded")
}
})
completionHandler()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.item_details.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:SellcollectViewCellController = collectionView.dequeueReusableCell(withReuseIdentifier: "CellSale", for: indexPath) as! SellcollectViewCellController
cell.cell_name_sale.text = self.item_details[indexPath.row]["item_name"]
print(cell.cell_name_sale.text)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selected")
self.performSegue(withIdentifier: "toDetail", sender: self.item_details[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toDetail"){
let nextVC = segue.destination as! ShowDetailsViewController
let item_details = sender as! Dictionary<String, String>
nextVC.item_details = item_details
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
Signs out a user when the button linked with the IBAction is clicked.
- parameter sender: Object that sent the action message
*/
#IBAction func log_out(_ sender: Any) {
do{
try! FIRAuth.auth()!.signOut()
self.performSegue(withIdentifier: "logout", sender: nil)
print("user logged out!")
} catch {
print("error")
}
}
}
And this is my second tab bar item
import Foundation
import UIKit
import Firebase
class BuyListViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {
let rootref = FIRDatabase.database().reference()
let storage = FIRStorage.storage()
var item_names = [String]()
var item_image_urls = [String]()
var item_details = [Dictionary<String, String>]()
var group = DispatchGroup()
var processRunning = false
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.load_data()
}
func load_data(){
self.group.enter()
self.processRunning = true
get_firebase_data(){
if(self.processRunning){
self.processRunning = false
self.group.leave()
}
}
self.group.notify(queue: DispatchQueue.main, execute: {
print("done")
})
}
func get_firebase_data(completionHandler: () -> ()){
rootref.child("Buy").observe(.value, with: { (snapshot) in
print("inside buy firebase")
if(snapshot.exists()){
var item_data = snapshot.value! as! Dictionary<String, AnyObject>
for(type_2_container,item_list) in item_data{
for(uid_container, item_detail_container) in item_list as! Dictionary<String, AnyObject>{
for(uid, item_detail) in item_detail_container as! Dictionary<String, AnyObject>{
var item_detail_dict = item_detail as? Dictionary<String,String>
var item_detail_temp = Dictionary<String, String>()
for key in (item_detail_dict?.keys)!{
item_detail_temp[key] = item_detail_dict?[key]
}
item_detail_temp["user_id"] = uid
self.item_details.append(item_detail_temp)
if(!self.item_names.contains(item_detail_dict!["item_name"]!)){
self.item_names.append(item_detail_dict!["item_name"]!)
self.item_image_urls.append(item_detail_dict!["item_image"]!)
}
}
}
}
print(self.item_details)
self.collectionView?.reloadData()
print("data was reloaded")
}
})
completionHandler()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.item_details.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:BuycollectViewCellController = collectionView.dequeueReusableCell(withReuseIdentifier: "CellBuy", for: indexPath) as! BuycollectViewCellController
cell.cell_name_buy.text = self.item_details[indexPath.row]["item_name"]
print(cell.cell_name_buy.text)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selected")
self.performSegue(withIdentifier: "toDetail", sender: self.item_details[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toDetail"){
let nextVC = segue.destination as! ShowDetailsViewController
let item_details = sender as! Dictionary<String, String>
nextVC.item_details = item_details
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func log_out(_ sender: Any) {
do{
try! FIRAuth.auth()!.signOut()
self.performSegue(withIdentifier: "logout", sender: nil)
print("user logged out!")
} catch {
print("error")
}
}
}
This is my custom collection view cell controller for the first tab item
import UIKit
class SellcollectViewCellController: UICollectionViewCell {
#IBOutlet weak var cell_name_sale: UILabel!
}
This is the second collection view cell controller
import UIKit
class BuycollectViewCellController: UICollectionViewCell {
#IBOutlet weak var cell_name_buy: UILabel!
}
This is a screenshot of my tab bar controller with the two tab items
Screenshot of the first bar item

Ambiguous reference to member tableview number rows in section

I'm loading some data from a web server and I'm getting ambiguous reference to member tableview numberOfRowsInSection? Below is my swift file. What am i missing here?
TableViewController.swift
import UIKit
class TableViewController: UITableViewController {
var viewModel:ViewModel!
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel = ViewModel()
self.tableView.delegate = viewModel
self.tableView.dataSource = viewModel
self.tableView.registerNib(UINib(nibName: "TableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: tableViewCellIdentifier)
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 50;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ViewModel.swift
import UIKit
class ViewModel: NSObject,UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource {
var dataArrayPosts: NSArray!
var posts:[Post] = []
override init() {
super.init()
let myURL = NSURL(string: "mydomainURLhere");
let requestPosts = NSMutableURLRequest(URL: myURL!);
requestPosts.HTTPMethod = "POST";
let postStringVars = ""
requestPosts.HTTPBody = postStringVars.dataUsingEncoding(NSUTF8StringEncoding);
let taskPosts = NSURLSession.sharedSession().dataTaskWithRequest(requestPosts){ data, response, error in
if error != nil{
print("error\(error)");
return;
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
//print(json)
if let category = json["Posts"] as? NSMutableArray{
//print(category)
_ = category
self.dataArrayPosts = json["Posts"] as! NSMutableArray;
dispatch_async(dispatch_get_main_queue()) {
self.posts.removeAll()
for item in self.dataArrayPosts {
let post = Post(postDesc: (item["postDesc"] as? String)!,imageName: (item["imageName"] as? String)!,bName: (item["bName"] as? String)!,postDate: (item["postDate"] as? String)!,postShowsUntil:(item["postShowsUntil"] as? String)!)
self.posts.append(post)
// Ambiguous on reloadData???????
self.tableView.reloadData()
}
}
}else{
dispatch_async(dispatch_get_main_queue()) {
print("Nothing Was Found")
}
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
taskPosts.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tableViewCellIdentifier, forIndexPath: indexPath) as! TableViewCell
let post = posts[indexPath.row]
cell.quoteTextLabel.text = post.postDesc
cell.nameLabel.text = post.bName
if let imageName = post.imageName where !imageName.isEmpty{
cell.photoView?.image = UIImage(named: imageName)
cell.photoWidthConstraint.constant = kDefaultPhotoWidth
cell.photoRightMarginConstraint.constant = kDefaultPhotoRightMargin
}
else {
cell.photoView?.image = nil
cell.photoWidthConstraint.constant = 0
cell.photoRightMarginConstraint.constant = 0
}
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! CollectionViewCell
return cell
}
}
None of the things that ViewModel inherits from expose a tableView property, your ViewModel needs a reference to your UITableViewController. As the ViewController owns the ViewModel it should be a weak reference, something like the following
class ViewModel: NSObject,UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource {
weak let tableViewController:UITableViewController
var dataArrayPosts: NSArray!
var posts:[Post] = []
override init(controller:UITableViewController) {
self.tableViewController = controller
super.init()
// ...
self.tableViewController.tableView.reloadData()
}
class TableViewController: UITableViewController {
var viewModel:ViewModel!
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel = ViewModel(controller:self)
// ...
}