Get a different numbers of images from collectionCell with use firebase - ios

How can i get a different numbers of images from collectionCell into scrollView with use firebase?
In my project i have three viewController's.
FirstVC - collectionView inside a tableView. CollectionView need for display the main images for scroll their. TableView need for display the name and and to scroll the table. (i.e. for those images which are in FirstVC in collectionCell).
SecondVC - only collectionView. Need for display the albums.
ThirdVC - only scrollView inside viewController. ScrollView need for a scroll images which are located in the images folder in firebase.
So when i click on album in secondVC on collectionCell i would like to see in thirdVC in scrollView images which are located in folder images in firebase for scrolling their.
My firebase struct is here:
{
"users" : {
"Y7EHcJuqQWZrVI1HBmNgccbPhm55" : {
"name" : "Photos",
"posts" : {
"images" : {
"image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"qwerty" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"posts2" : {
"images" : {
"image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"qwerty" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city2.jpg?alt=media&token=64509e18-9884-4449-a081-c67393a7d82a"
},
"posts3" : {
"images" : {
"image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image2" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"qwerty" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/oko1.jpg?alt=media&token=fedea2cb-93b1-496c-9392-0b95f4ada7b5"
}
}
}
}
And my project in googleDrive, because I was faced with the problem of loading the project on github. My project is very simple, but I can't solve the problem about which wrote above.
projectTestGoogleDrive
My project code:
FirstVC:
import UIKit
import Firebase
import SDWebImage
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var nameArray = [String]()
var addressArray = [String]()
var postImage = [String](), postImage2 = [String](), postImage3 = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadName()
loadImages()
tableView.allowsSelection = true
}
func loadName() {
FIRDatabase.database().reference().child("users").
observe(FIRDataEventType.childAdded, with: {(snapshot) in
let value = snapshot.value! as! NSDictionary
self.nameArray.append(value["name"] as? String ?? "")
})
}
func loadImages() {
FIRDatabase.database().reference().child("users").
observe(FIRDataEventType.childAdded, with: {(snapshot) in
let values = snapshot.value! as! NSDictionary
let posts = values["posts"] as? NSDictionary //[String: AnyObject]
let posts2 = values["posts2"] as? NSDictionary //[String: AnyObject]
let posts3 = values["posts3"] as? NSDictionary //[String: AnyObject]
self.postImage.append(posts?["qwerty"] as? String ?? "")
self.postImage2.append(posts2?["qwerty"] as? String ?? "")
self.postImage3.append(posts3?["qwerty"] as? String ?? "")
self.tableView.reloadData()
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue2" {
if let indexPaths = self.tableView.indexPathForSelectedRow {
let indexPath = indexPaths as NSIndexPath
let dvc = segue.destination as! CollectionViewController
let imagesArray = [self.postImage[indexPath.row],
self.postImage2[indexPath.row],
self.postImage3[indexPath.row]]
dvc.images = imagesArray.filter({ !($0.isEmpty) })
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.userNameLabel.text = nameArray[indexPath.row]
let array = [postImage[indexPath.row],
postImage2[indexPath.row],
postImage3[indexPath.row]]
cell.postImageArray = array.filter({ !($0.isEmpty) })
return cell
}
}
SecondVC:
import UIKit
import SDWebImage
class CollectionViewController: UICollectionViewController {
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue3" {
if let indexPaths = self.collectionView?.indexPathsForSelectedItems {
let indexPath = indexPaths[0] as NSIndexPath
let dvc = segue.destination as! ViewControllerScrollView
dvc.images = [images[indexPath.item]]
}
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell2
cell.imageView.sd_setImage(with: URL(string: images[indexPath.item]))
return cell
}
}
ThirdVC:
import UIKit
class ViewControllerScrollView: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0..<images.count {
let imageView = UIImageView()
imageView.sd_setImage(with: URL(string: images[i]))
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height)
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Related

Swift: Show data from tableView to another ViewController (JSON, Alamorife, AlamofireImage)

I'm trying to do an app in which the data were obtained from JSON.
In the picture below you can see the project:
Project
If we click on the photo opens the details page. The problem is because I do not know how to pick up the data shown in the details page. Please help me.
Here is the code
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {
#IBOutlet weak var searchbarValue: UISearchBar!
weak open var delegate: UISearchBarDelegate?
#IBOutlet weak var tableView: UITableView!
var albumArray = [AnyObject]()
var url = ("https://jsonplaceholder.typicode.com/photos")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.searchbarValue?.delegate = self
Alamofire.request("https://jsonplaceholder.typicode.com/photos").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar[].arrayObject {
self.albumArray = resData as [AnyObject]; ()
}
if self.albumArray.count > 0 {
self.tableView.reloadData()
}
}
}
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) // called when text ends editing
{
callAlamo(searchTerm: searchbarValue.text!)
}
func callAlamo(searchTerm: String)
{
Alamofire.request("https://jsonplaceholder.typicode.com/photos").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar[].arrayObject {
self.albumArray = resData as [AnyObject]; ()
}
if self.albumArray.count > 0 {
self.tableView.reloadData()
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return albumArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CostumTableViewCell
let title = albumArray[indexPath.row]
cell?.titleLabel?.text = title["title"] as? String
//cell?.url?.image = UIImage(data: title as! Data)
let imageUrl = title["thumbnailUrl"] as? String
//print(imageUrl)
let urlRequest = URLRequest(url: URL(string: imageUrl!)!)
Alamofire.request(urlRequest).responseImage { response in
if let image = response.result.value {
// print("image downloaded: \(title["url"])")
cell?.url?.image = image
}
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow?.row
let vc = segue.destination as! DetailsViewController
//here should be the code
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Also you can see the DetailsViewController code:
import UIKit
class DetailsViewController: UIViewController {
var image2 = UIImage()
var title2 = String()
#IBOutlet var mainImageView: UIImageView!
#IBOutlet var songTitle: UILabel!
override func viewDidLoad() {
songTitle.text = title2
mainImageView.image = image2
}
}
You can easily pass value from tableview to detail view using the below code :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow
let cell : CostumTableViewCell = self.tableView.cellForRow(at: indexPath!) as! CostumTableViewCell
let vc = segue.destination as! DetailsViewController
vc.image2 = cell.url.image!
vc.title2 = cell.titleLabel.text!
}
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {
var customArr = [CustomElement]()
var arr = [Any]()
// In viewDidLoad , you can append element to customArr
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var image = customArr[indexpath.row].image
var title = customArr[indexpath.row].title
arr.append(image)
arr.append(title)
performSegue(withIdentifier: "showDetails", sender: arr)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow?.row
if segue.identifier = "showDetails" {
if let vc = segue.destination as! DetailsViewController {
vc.arr = sender
}
}
//here should be the code
}
}
class DetailsViewController: UIViewController {
var arr = [Any]()
}

Perform Segue from UICollectionViewCell

So I'm creating a blog app, and on the home news feed collection view (imageCollection, loaded from firebase database) I have a button. This button title depends on the Category of the image. What i'm having an issue with is performing the segue in the UICollectionViewCell class. I ran the button action with the print statement, and it worked. But when i try to add performSegue, well it doesn't let me. (Use of unresolved identifier 'performSegue')
Any tips? thank you!
P.S. i'm still fairly new to swift, so if i come off a little ignorant, i apologize
My ViewController
import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet weak var popImageCollection: UICollectionView!
#IBOutlet weak var imageCollection: UICollectionView!
var customImageFlowLayout = CustomImageFlowLayout()
var popImageFlowLayout = PopImagesFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var homePageTextArray = [NewsTextModel]()
var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
dbRef = Database.database().reference().child("images")
dbPopularRef = Database.database().reference().child("popular")
loadDB()
loadImages()
loadText()
customImageFlowLayout = CustomImageFlowLayout()
popImageFlowLayout = PopImagesFlowLayout()
imageCollection.backgroundColor = .white
popImageCollection.backgroundColor = .white
// Do any additional setup after loading the view, typically from a nib.
}
func loadText() {
dbRef.observe(DataEventType.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
self.homePageTextArray.removeAll()
for homeText in snapshot.children.allObjects as! [DataSnapshot] {
let homeTextObject = homeText.value as? [String: AnyObject]
let titleHome = homeTextObject?["title"]
let categoryButtonText = homeTextObject?["category"]
self.imageCollection.reloadData()
let homeLabels = NewsTextModel(title: titleHome as! String?, buttonText: categoryButtonText as! String?)
self.homePageTextArray.append(homeLabels)
}
}
})
}
func loadImages() {
popImageArray.append(UIImage(named: "2")!)
popImageArray.append(UIImage(named: "3")!)
popImageArray.append(UIImage(named: "4")!)
self.popImageCollection.reloadData()
}
func loadDB() {
dbRef.observe(DataEventType.value, with: { (snapshot) in
var newImages = [BlogInsta]()
for BlogInstaSnapshot in snapshot.children {
let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.imageCollection {
return images.count
} else {
return popImageArray.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollection {
let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
let image = images[indexPath.row]
let text: NewsTextModel
text = homePageTextArray[indexPath.row]
cell.categoryButton.setTitle(text.buttonText, for: .normal)
cell.newTitleLabel.text = text.title
cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
return cell
} else {
let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
let popPhotos = popImageArray[indexPath.row]
cellB.popularImageView.image = popPhotos
cellB.popularImageView.frame.size.width = view.frame.size.width
return cellB
}
}
}
My ImageCollectionViewCell.swift
import UIKit
import Foundation
class ImageCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var categoryButton: UIButton!
#IBOutlet weak var newTitleLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBAction func categoryButtonAction(_ sender: Any) {
if categoryButton.currentTitle == "Fashion" {
print("Fashion Button Clicked")
performSegue(withIdentifier: "homeToFashion", sender: self)
}
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
}
}
You need a custom delegate. Do this:
protocol MyCellDelegate {
func cellWasPressed()
}
// Your cell
class ImageCollectionViewCell: UICollectionViewCell {
var delegate: MyCellDelegate?
#IBAction func categoryButtonAction(_ sender: Any) {
if categoryButton.currentTitle == "Fashion" {
print("Fashion Button Clicked")
self.delegate?.cellWasPressed()
}
}
}
// Your viewcontroller must conform to the delegate
class ViewController: MyCellDelegate {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollection {
let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
// set the delegate
cell.delegate = self
// ...... rest of your cellForRowAtIndexPath
}
// Still in your VC, implement the delegate method
func cellWasPressed() {
performSegue(withIdentifier: "homeToFashion", sender: self)
}
}
You should use your own delegate. It is already described here
performSegue(withIdentifier:sender:) won't work from cell because it is UIViewController metod.
also you can make use of closure

How to handle tableview cell clicks and segues when delegate and datasource class is separate?

I tried to separate TableViewDelegate and TableViewDataSource to a separate class from ViewController and I'm facing a couple of problems now.
First problem:
App loads the tableview with all content but when I click on it or try to scroll all data disappears.
Second problem:
On click cell should link to another view where is more content displayed. I push data to this view using function. But when I separated the delegate and datasource to other class it doesnt work.
prepare(for segue: UIStoryboardSegue, sender: Any?)
Here is my code for view controller:
import UIKit
import Foundation
import os
class FirstViewController: UIViewController {
#IBOutlet weak var tableview: UITableView!
#IBOutlet weak var offlineModePicture: UIBarButtonItem!
#IBOutlet weak var refresh_button: UIBarButtonItem!
var wyznania_page = 0 // page
var isNewDataLoading = false
var wyznania = [[WyznanieData](),[WyznanieData](),[WyznanieData](),[WyznanieData](),[WyznanieData]()]
let activitiyViewController = ActivityViewController(message: "Ładowanie...😇")
override func viewDidLoad() {
super.viewDidLoad()
wyznania[wyznania_page].append(WyznanieData(date: "date", story: "story", sharedLink: "link", tag: "asd", fav: false, page: 1)!)
wyznania[wyznania_page].append(WyznanieData(date: "date", story: "story", sharedLink: "link", tag: "asd", fav: false, page: 1)!)
wyznania[wyznania_page].append(WyznanieData(date: "date", story: "story", sharedLink: "link", tag: "asd", fav: false, page: 1)!)
self.navigationController?.navigationBar.sizeToFit()
view.backgroundColor = UIColor.black
tabBarController?.tabBar.barTintColor = ColorsUI.bar
tabBarController?.tabBar.tintColor = UIColor.white
navigationController?.navigationBar.barTintColor = ColorsUI.bar
navigationController?.navigationBar.tintColor = UIColor.white
let customDelegate = TableViewDelegate(dataForRows: wyznania[wyznania_page])
self.tableview.delegate = customDelegate
self.tableview.dataSource = customDelegate
}
override internal var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch(segue.identifier ?? "") {
case "ShowDetail":
guard let storyDetailViewController = segue.destination as? WyznanieViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
guard let selectedStopCell = sender as? Wyznanie else {
fatalError("Unexpected sender: \(String(describing: sender))")
}
guard let indexPath = tableview.indexPath(for: selectedStopCell) else {
fatalError("The selected cell is not being displayed by the table")
}
let selectedStory = wyznania[wyznania_page][(indexPath as NSIndexPath).row]
storyDetailViewController.wyznanie = selectedStory
default:
fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
}
}
#IBAction func unwindToList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? WyznanieViewController, let story = sourceViewController.wyznanie {
if let selectedIndexPath = tableview.indexPathForSelectedRow {
// Update an existing story.
print("updating")
wyznania[wyznania_page][selectedIndexPath.row] = story
tableview.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
// Add a new story
print("adding new")
}
}
}
}
And my Delegate and DataSource class:
[import UIKit
class TableViewDelegate: NSObject,UITableViewDelegate,UITableViewDataSource {
var wyznania = \[WyznanieData\]()
init(dataForRows: \[WyznanieData\]) {
self.wyznania = dataForRows
super.init()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return wyznania.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "story_cell", for:indexPath) as? Wyznanie else {
fatalError("The dequeued cell is not an instance of WyznanieTableViewCell.")
}
let wyznanie = wyznania\[indexPath.row\]
cell.date.text = wyznanie.date
cell.story.text = wyznanie.story
cell.story.setContentOffset(CGPoint.zero, animated: true)
cell.story.textColor = UIColor.white
cell.backgroundColor = ColorsUI.cell_backgroung
cell.layer.borderWidth = 3.0
cell.layer.borderColor = ColorsUI.cell_borderColor
return cell
}
}]
1
[]
Try making your delegate variable global. it must be deallocation when goes out of scope in viewDidLoad (dataSource and delegate are weak in UITableView).
Extract following declaration global.
var customDelegate: TableViewDelegate!
then in viewDidLoad do following
customDelegate = TableViewDelegate(dataForRows: wyznania[wyznania_page])

Passing data with segue in the tableViewCell

I want to passing data with segue in the tableViewCell,from BulletinBoadrViewController to BbDetailViewController
class BulletinBoadrViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var bulletinBoards = [BulletinBoard]()
override func viewDidLoad() {
super.viewDidLoad()
bulletinBoards = BulletinBoard.downloadAllBulletinBoard()
self.tableView.reloadData()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return bulletinBoards.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! BulletinBoardTableViewCell
let bulletinBoard = bulletinBoards[indexPath.row]
cell.bulletinBoard = bulletinBoard
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "gotodetail", sender: indexPath)
print("Row \(indexPath.row)selected")
}
func prepareForSegue(segue: UIStoryboardSegue, sender: Any!) {
if segue.identifier == "gotodetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let destVC = segue.destination as! BdDeatilViewController
let new = bulletinBoards[indexPath.row]
destVC.bulletinBoard = new
}
}
}
and it's BdDeailViewController
class BdDeatilViewController:UIViewController {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var contentLabel: UITextView!
#IBAction func backtobb(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
var x = [BulletinBoard]()
var bulletinBoard : BulletinBoard!{
didSet{
self.updateUI()
}
}
func updateUI() {
timeLabel.text = bulletinBoard.time
titleLabel.text = bulletinBoard.title
contentLabel.text = bulletinBoard.content
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
and tableViewCell's data is taking from local json file, it's BulletinBoard code
class BulletinBoard {
var title:String?
var time:String?
var content:String?
init(title:String,time:String,content:String) {
self.title = title
self.time = time
self.content = content
}
init(bulletinBoardDictionary:[String:Any]) {
self.title = bulletinBoardDictionary["title"] as? String
self.time = bulletinBoardDictionary["time"] as? String
self.content = bulletinBoardDictionary["content"] as? String
}
static func downloadAllBulletinBoard() -> [BulletinBoard] {
var bulletinBoards = [BulletinBoard]()
//get the json data from the file
let jsonFile = Bundle.main.path(forResource: "BulletinBoardData", ofType: "json")
let jsonFileURL = URL(fileURLWithPath: jsonFile!)
let jsonData = try? Data(contentsOf: jsonFileURL)
//turn the json data into foundation objects (bulletinBoards)
if let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {
let bulletinBoardDictionaries = jsonDictionary["BulletinBoard"] as! [[String:Any]]
for bulletinBoardDictionary in bulletinBoardDictionaries {
let newBulletinBoard = BulletinBoard(bulletinBoardDictionary: bulletinBoardDictionary)
bulletinBoards.append(newBulletinBoard)
}
}
return bulletinBoards
}
}
Finally,it's my StoryBoard
https://i.stack.imgur.com/JcgdH.png1
Can anyone solve my problem?Thanks!
I think you should retrieve indexPath from sender in prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: Any!) {
if segue.identifier == "gotodetail" {
if let indexPath = sender as? IndexPath {
let destVC = segue.destination as! BdDeatilViewController
let new = bulletinBoards[indexPath.row]
destVC.bulletinBoard = new
}
}
}
and update the UI in the viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.updateUI()
}

Display bigger Image in next view Controller from CollectionView

I used SDWEBIMAGE to display images in a UICollectionView from an API. Now, When the user taps on the image in a collectionview, i want to open the image in the next viewcontroller. I am able to display the title in the next View, but couldn't display the image because i want not able to assign it at UIImage. I am using swift.
can anyone please suggest me a way on how to do it.
import UIKit
import SDWebImage
private let reuseIdentifier = "Celll"
var titles = [String]()
var imagecollection = [String]()
class CollectionViewController: UICollectionViewController,
UICollectionViewDelegateFlowLayout {
let sectioninserts = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
var titles = [String]()
var imagecollection = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://api.myjson.com/bins/537mf")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
if error != nil {
print("error")
}else {
if let urlcontent = data {
do {
let jsoncontent = try NSJSONSerialization.JSONObjectWithData(urlcontent, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
// print(jsoncontent)
if jsoncontent.count > 0 {
let items = jsoncontent["items"] as! NSArray
for item in items as! [[String:String]]{
self.imagecollection.append(item["media"]!)
print(self.imagecollection)
self.titles.append(item["title"]!)
print(self.titles)
}
dispatch_async(dispatch_get_main_queue(), {
self.collectionView?.reloadData()
})
}
} catch {}
}
}
}
task.resume()
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return imagecollection.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.titleee.text = self.titles[indexPath.row]
let imagestring = imagecollection[indexPath.row]
let imageurl = NSURL(string: imagestring)
cell.disp.sd_setImageWithURL(imageurl, placeholderImage: UIImage(named: "loading.gif"), options: SDWebImageOptions.ProgressiveDownload, completed: nil)
return cell
}
func collectionView(collectionView: UICollectionView!,
layout collectionViewLayout: UICollectionViewLayout!,
sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize {
return CGSize(width: 170, height: 300)
}
func collectionView(collectionView: UICollectionView!,
layout collectionViewLayout: UICollectionViewLayout!,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectioninserts
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detail" {
let cell = sender as! CollectionViewCell
let indexPath = collectionView?.indexPathForCell(cell)
let vc = segue.destinationViewController as! DetailViewController
vc.label = self.titles[indexPath!.row]
enter code here**
Step-1
on that DetailViewController create the another one String like MediaStr
class DetailViewController: UIViewController {
var MediaStr: String
var label: String
override func viewDidLoad() {
super.viewDidLoad()
print (MediaStr)
}
}
Step-2
on your first VC Call Direclt like
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detail" {
let cell = sender as! CollectionViewCell
let indexPath = collectionView?.indexPathForCell(cell)
let vc = segue.destinationViewController as! DetailViewController
vc.label = self.titles[indexPath!.row]
// add the folloing line
vc.MediaStr = self. imagecollection[indexPath!.row]
}
Step-3
for image loading purpose
import SDWebImage
class DetailViewController: UIViewController {
var MediaStr: String
var label: String
override func viewDidLoad() {
super.viewDidLoad()
print (MediaStr)
if let imagestring = MediaStr
{
yourImageViewName_setImageWithURL(NSURL(string: imagestring), placeholderImage: UIImage(named: "loading.gif"), options: SDWebImageOptions.ProgressiveDownload, completed: nil)
}
}
}

Resources