What’s the “cleaner” way to pass data between UIViewControllers - ios

I gotta populate a UIViewController using data from a UITableView. So, when the user click on each UITableview Cell, another screen should appear filled with some data from the respective clicked UITableView Cell. I don't have certain if I should do it using "Segue" to the other screen, or if there's any better and "clean" way to do that. What would you guys recommend me to do?
Storyboard:
Details Screen:
import UIKit
class TelaDetalheProdutos: UIViewController {
#IBOutlet weak var ImageView: UIImageView!
#IBOutlet weak var labelNomeEDesc: UILabel!
#IBOutlet weak var labelDe: UILabel!
#IBOutlet weak var labelPor: UILabel!
#IBOutlet weak var labelNomeProduto: UILabel!
#IBOutlet weak var labelDescricao: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
ViewController:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UITableViewDataSource {
#IBOutlet weak var tableViewTopSell: UITableView!
#IBOutlet var collectionView: UICollectionView!
#IBOutlet weak var collectionViewBanner: UICollectionView!
var dataSource: [Content] = [Content]()
var dataBanner: [Banner] = [Banner]()
var dataTopSold: [Top10] = [Top10]()
override func viewDidLoad() {
super.viewDidLoad()
//SetupNavBarCustom
self.navigationController?.navigationBar.CustomNavigationBar()
let logo = UIImage(named: "tag.png")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
//CallAPIData
getTopSold { (data) in
DispatchQueue.main.async {
self.dataTopSold = data
self.tableViewTopSell.reloadData()
}
}
getBanner { (data) in
DispatchQueue.main.async {
self.dataBanner = data
self.collectionViewBanner.reloadData()
}
}
getAudiobooksAPI { (data) in
DispatchQueue.main.async {
self.dataSource = data
self.collectionView.reloadData()
}
}
}
//CollectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if (collectionView == self.collectionView) {
return self.dataSource.count
}else{
return self.dataBanner.count
}}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (collectionView == self.collectionView) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
let content = self.dataSource[indexPath.item]
cell.bookLabel.text = content.descricao
cell.bookImage.setImage(url: content.urlImagem, placeholder: "")
return cell
}else if (collectionView == self.collectionViewBanner) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCellBanner", for: indexPath) as! CollectionViewCell
let content = self.dataBanner[indexPath.item]
cell.bannerImage.setImage(url: content.urlImagem, placeholder: "")
return cell
}
return UICollectionViewCell()
}
//TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataTopSold.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "topSoldCell", for: indexPath) as! TableViewCell
let content = self.dataTopSold[indexPath.item]
cell.labelNomeTopSell.text = content.nome
cell.imageViewTopSell.setImage(url: content.urlImagem, placeholder: "")
cell.labelPrecoDe.text = "R$ \(content.precoDe)"
cell.labelPrecoPor.text = "R$ 119.99"
return cell
}
}
extension UIImageView{
func setImage(url : String, placeholder: String, callback : (() -> Void)? = nil){
self.image = UIImage(named: "no-photo")
URLSession.shared.dataTask(with: NSURL(string: url)! as URL, completionHandler: { (data, response, error) -> Void in
guard error == nil else{
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
self.image = image
if let callback = callback{
callback()
}
})
}).resume()
}
}

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
switch segue.destination{
case is DestinationViewController:
let vc = segue.destination as! DestinationViewController
//Share your data to DestinationViewController
//Like vc.variableName = value
default:
break
}
}

Make sure that the data your sharing is going to an actual variable like var artistToDisplay: String? in the DestinationViewController, and not an IBOutlet.
You may also need to implement the tableView(_:didSelectRowAt:_) and performSegue(withIdentifier:sender:) methods to begin the segue.

Related

How to show data in my application? Swift and Firebase

I am facing a problem in my application. When I run my application in the emulator, I don't get any data and just a white screen.
I decided to use Firestore as a backend. Below I provide the code and hope you can help me.
ViewController
class ViewController: UIViewController {
#IBOutlet weak var cv: UICollectionView!
var channel = [Channel]()
override func viewDidLoad() {
super.viewDidLoad()
self.cv.delegate = self
self.cv.dataSource = self
let db = Firestore.firestore()
db.collection("content").getDocuments() {( quarySnapshot, err) in
if let err = err {
print("error")
} else {
for document in quarySnapshot!.documents {
if let name = document.data()["title"] as? Channel {
self.channel.append(name)
}
}
self.cv.reloadData()
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return channel.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCell
let indexChannel = channel[indexPath.row]
cell.setup(channel: indexChannel)
return cell
}
}
This is my cell
class ContentCell: UICollectionViewCell {
#IBOutlet weak var channelText: UILabel!
#IBOutlet weak var subtitle: UITextView!
func setup(channel: Channel) {
channelText.text = channel.title
subtitle.text = channel.subtitle
}
}
If you need additional information - write
Your problem is here
if let name = document.data()["title"] as? Channel {
self.channel.append(name)
}
you can't cast a String to a Custom data type (Channel) , so according to your data you can try this
if let title = document.data()["title"] as? String , let subtitle = document.data()["subtitle"] as? String {
let res = Channel(title:title,subtitle:subtitle)
self.channel.append(res)
}

Displaying the Image From API using DidSelectRow

I am trying to send the data in including image from one view controller to another . The data is fetching from API . The data is successfully loaded into first view controller including image but when I try to reuse same code with didSelectRow function I am getting following errors . Cannot assign value of type 'Data?' to type 'UIImage' . The error on this line dc.imagemovie = presenter.getImageData(by: row). Here is the code to fetch the data from API.
class MoviePresenter: MoviePresenterProtocol {
private let view: MovieViewProtocol
private let networkManager: NetworkManager
private var movies = [Movie]()
private var cache = [Int: Data]()
var rows: Int {
return movies.count
}
init(view: MovieViewProtocol, networkManager: NetworkManager = NetworkManager()) {
self.view = view
self.networkManager = networkManager
}
func getMovies() {
let url = "https://api.themoviedb.org/3/movie/popular?language=en-US&page=3&api_key=6622998c4ceac172a976a1136b204df4"
networkManager.getMovies(from: url) { [weak self] result in
switch result {
case .success(let response):
self?.movies = response.results
self?.downloadImages()
DispatchQueue.main.async {
self?.view.resfreshTableView()
}
case .failure(let error):
DispatchQueue.main.async {
self?.view.displayError(error.localizedDescription)
}
}
}
}
func getTitle(by row: Int) -> String? {
return movies[row].originalTitle
}
func getOverview(by row: Int) -> String? {
return movies[row].overview
}
func getImageData(by row: Int) -> Data? {
return cache[row]
}
private func downloadImages() {
let baseImageURL = "https://image.tmdb.org/t/p/w500"
let posterArray = movies.map { "\(baseImageURL)\($0.posterPath)" }
let group = DispatchGroup()
group.enter()
for (index, url) in posterArray.enumerated() {
networkManager.getImageData(from: url) { [weak self] data in
if let data = data {
self?.cache[index] = data
}
}
}
group.leave()
group.notify(queue: .main) { [weak self] in
self?.view.resfreshTableView()
}
}
}
Here is the code in view controller to display the data into table view cell .
class MovieViewController: UIViewController {
#IBOutlet weak var userName: UILabel!
#IBOutlet weak var tableView: UITableView!
private var presenter: MoviePresenter!
var finalname = ""
override func viewDidLoad() {
super.viewDidLoad()
userName.text = "Hello: " + finalname
setUpUI()
// configure presenter
presenter = MoviePresenter(view: self)
presenter.getMovies()
}
private func setUpUI() {
tableView.dataSource = self
tableView.delegate = self
}
#IBAction func selectSegment(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0{
setUpUI()
presenter = MoviePresenter(view: self)
presenter.getMovies()
}
}
}
extension MovieViewController: MovieViewProtocol {
func resfreshTableView() {
tableView.reloadData()
}
func displayError(_ message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
let doneButton = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(doneButton)
present(alert, animated: true, completion: nil)
}
}
extension MovieViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
presenter.rows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell
let row = indexPath.row
let title = presenter.getTitle(by: row)
let overview = presenter.getOverview(by: row)
let data = presenter.getImageData(by: row)
cell.configureCell(title: title, overview: overview, data: data)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dc = storyboard?.instantiateViewController(withIdentifier: "MovieDeatilsViewController") as! MovieDeatilsViewController
let row = indexPath.row
dc.titlemovie = presenter.getTitle(by: row) ?? ""
dc.overview = presenter.getOverview(by: row) ?? ""
**dc.imagemovie = presenter.getImageData(by: row)**
self.navigationController?.pushViewController(dc, animated: true)
}
}
extension MovieViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
Here is the code for display the data .
class MovieDeatilsViewController: UIViewController {
#IBOutlet weak var movieImage: UIImageView!
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var movieOverview: UILabel!
var titlemovie = ""
var overview = ""
var imagemovie = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
movieTitle.text = titlemovie
movieOverview.text = overview
movieImage.image = imagemovie
}
}
You need to return UIImage :
class MoviePresenter: MoviePresenterProtocol {
...
// Convert data to UIImage
func getImageData(by row: Int) -> UIImage? {
return UIImage(data: cache[row])
}
You need yo use UIImage and UIImage view to configure cell :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MovieViewCell.identifier, for: indexPath) as! MovieViewCell
let row = indexPath.row
let title = presenter.getTitle(by: row)
let overview = presenter.getOverview(by: row)
let image = presenter.getImageData(by: row)
// cell is now configured with an image
cell.configureCell(title: title, overview: overview, image: image)
return cell
}
You need to modify cell.configureCell to handle UIImage? instead of data.
When selecting a cell you must use UIImage to init VC :
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dc = storyboard?.instantiateViewController(withIdentifier: "MovieDeatilsViewController") as! MovieDeatilsViewController
let row = indexPath.row
dc.titlemovie = presenter.getTitle(by: row) ?? ""
dc.overview = presenter.getOverview(by: row) ?? ""
dc.imagemovie = presenter.getImageData(by: row)// now an image
self.navigationController?.pushViewController(dc, animated: true)
}
Use UIImage to initialise image movie in detail vc :
class MovieDeatilsViewController: UIViewController {
#IBOutlet weak var movieImageView: UIImageView! // Image view here
#IBOutlet weak var movieTitle: UILabel!
#IBOutlet weak var movieOverview: UILabel!
var titlemovie = ""
var overview = ""
var imagemovie : UIImage?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated: animated)
movieTitle.text = titlemovie
movieOverview.text = overview
// here you could also display a default image
// if image is not set
if let image = imagemovie {
movieImageView.image = image
}
}
}

pass image to another view when clicked on tableview cell. The image is fetched from json data and initialised with alamofire

i am fetching json data from url and displaying it in tableview. I want to image in tableview to another view controller when clicked on tableview cell. My another label are showing but dont know how to write code for image in didselectrowatindexpath method of tableview
my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
//getting hero for specified position
let hero: Hero
hero = heroes[indexPath.row]
//displaying values
cell.labelName.text = hero.name
cell.labelTeam.text = hero.team
cell.labelRealName.text = hero.realname
cell.labelAppear.text = hero.firstappearance
cell.labelPublish.text = hero.publisher
//displaying image
Alamofire.request(hero.imageUrl!).responseImage { (response) in
debugPrint(response)
if let image = response.result.value {
cell.heroImage.image = image
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let heroesDetails:HeroesDetailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "HeroesDetailsViewController") as! HeroesDetailsViewController
heroesDetails.strlabelTeam = heroes[indexPath.row].team
heroesDetails.strlabelName = heroes[indexPath.row].name
heroesDetails.strlabelAppear = heroes[indexPath.row].firstappearance
heroesDetails.strlabelPublish = heroes[indexPath.row].publisher
heroesDetails.strlabelRealName = heroes[indexPath.row].realname
self.navigationController?.pushViewController(heroesDetails, animated: true)
}
my heroesdetailviewcontroller file where i want to display code:
import UIKit
class HeroesDetailsViewController: UIViewController {
#IBOutlet weak var detailsImg: UIImageView!
#IBOutlet weak var detailsName: UILabel!
#IBOutlet weak var detailsRealName: UILabel!
#IBOutlet weak var detailsTeam: UILabel!
#IBOutlet weak var detailsAppear: UILabel!
#IBOutlet weak var detailsPublisher: UILabel!
var strheroImage: UIImage!
var strlabelName: String!
var strlabelTeam: String!
var strlabelAppear: String!
var strlabelPublish: String!
var strlabelRealName: String!
override func viewDidLoad() {
super.viewDidLoad()
detailsImg.image = strheroImage
detailsName.text = strlabelName
detailsRealName.text = strlabelRealName
detailsTeam.text = strlabelTeam
detailsAppear.text = strlabelAppear
detailsPublisher.text = strlabelPublish
// Do any additional setup after loading the view.
}
}
my modal file:
class Hero{
var name:String?
var team:String?
var imageUrl:String?
var realname:String?
var firstappearance:String?
var publisher:String?
init(name:String?, team:String?, imageUrl:String?, realname:String?, firstappearance:String?, publisher:String?) {
self.name = name
self.team = team
self.imageUrl = imageUrl
self.realname = realname
self.firstappearance = firstappearance
self.publisher = publisher
}
}
my tableviewcell.swift file:
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var heroImage: UIImageView!
#IBOutlet weak var labelName: UILabel!
#IBOutlet weak var labelTeam: UILabel!
#IBOutlet weak var labelAppear: UILabel!
#IBOutlet weak var labelPublish: UILabel!
#IBOutlet weak var labelRealName: UILabel!
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 main viewcontroller.swift file which contains all code:
import UIKit
import Alamofire
import AlamofireImage
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
//MARK: IBOUTLETS
#IBOutlet weak var tableviewHeroes: UITableView!
// Web API Url
let URL_GET_DATA = "https://simplifiedcoding.net/demos/marvel/"
// List to store Heroes
var heroes = [Hero]()
//implementing uirefreshcontrol to tableview
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(ViewController.handleRefresh), for: .valueChanged)
refreshControl.tintColor = UIColor.init(red: 217/255, green: 133/255, blue: 199/255, alpha: 1)
return refreshControl
}()
override func viewDidLoad() {
super.viewDidLoad()
self.tableviewHeroes.addSubview(self.refreshControl)
//fetching data from web api
Alamofire.request(URL_GET_DATA).responseJSON { (response) in
//getting json
if let json = response.result.value {
//converting json to NSArray
let heroesArray:NSArray = json as! NSArray
//traversing through all elements of the array
for i in 0..<heroesArray.count {
//adding heroes value to hero list
self.heroes.append(Hero(
name: (heroesArray[i] as AnyObject).value(forKey: "name") as? String, team: (heroesArray[i] as AnyObject).value(forKey: "team") as? String, imageUrl: (heroesArray[i] as AnyObject).value(forKey: "imageurl") as? String,
realname: (heroesArray[i] as AnyObject).value(forKey: "realname") as? String, firstappearance: (heroesArray[i] as AnyObject).value(forKey: "firstappearance") as? String, publisher: (heroesArray[i] as AnyObject).value(forKey: "publisher") as? String ))
}
//display data in tableview
self.tableviewHeroes.reloadData()
}
}
self.tableviewHeroes.reloadData()
}
func handleRefresh(refreshControl: UIRefreshControl) {
self.tableviewHeroes.reloadData()
refreshControl.endRefreshing()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return heroes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
//getting hero for specified position
let hero: Hero
hero = heroes[indexPath.row]
//displaying values
cell.labelName.text = hero.name
cell.labelTeam.text = hero.team
cell.labelRealName.text = hero.realname
cell.labelAppear.text = hero.firstappearance
cell.labelPublish.text = hero.publisher
//displaying image
Alamofire.request(hero.imageUrl!).responseImage { (response) in
debugPrint(response)
if let image = response.result.value {
cell.heroImage.image = image
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let heroesDetails:HeroesDetailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "HeroesDetailsViewController") as! HeroesDetailsViewController
let hero: Hero
hero = heroes[indexPath.row]
let image : UIImage = UIImage(data: hero.imageUrl)
heroesDetails.strlabelTeam = heroes[indexPath.row].team
heroesDetails.strlabelName = heroes[indexPath.row].name
heroesDetails.strlabelAppear = heroes[indexPath.row].firstappearance
heroesDetails.strlabelPublish = heroes[indexPath.row].publisher
heroesDetails.strlabelRealName = heroes[indexPath.row].realname
heroesDetails.strheroImage = image
self.navigationController?.pushViewController(heroesDetails, animated: true)
}
}
You should use Caches policy instead of passing downloaded image from one VC to another. Larger image could take time to download, user can not wait for it before tapping the table view cell.
For more details please see Image Cache Section
https://github.com/Alamofire/AlamofireImage
In your didSelectRowAt indexPath function, before sending image to different viewController try to convert the data into image first, then send it:
First declare a global image variable:
var imageArray = [UIImage]()
Then assign the image you get from alamofireImage to this variable in your cellForRowAt indexPath function:
if let image = response.result.value {
cell.heroImage.image = image
self.imageArray.append(image)
}
Then pass it :
heroesDetails.strlabelTeam = heroes[indexPath.row].team
heroesDetails.strlabelName = heroes[indexPath.row].name
heroesDetails.strlabelAppear = heroes[indexPath.row].firstappearance
heroesDetails.strlabelPublish = heroes[indexPath.row].publisher
heroesDetails.strlabelRealName = heroes[indexPath.row].realname
heroesDetails.strheroImage = self.imageArray[indexPath.row]
1st View Controller:
import UIKit
import Alamofire
import ObjectMapper
var homeScreenData = [HomeDataModel]()
func homeScreenDataAPI(){
var params : Parameters?
params =
[
"user_id" : id ?? 0,
]
print(params as Any)
self.view.makeToastActivity(.center)
ApiCallWithHeader(url : “homeDataAPI” , params : params!) { responseObject, error in
// use responseObject and error here
print("responseObject = \(String(describing: responseObject)); error = \(String(describing: error))")
let JSON = responseObject
if(JSON?["status"] as? String == "success") {
if let responseData = (JSON?["data"] as? [Dictionary<String, AnyObject>]) {
if let homeScreenDataValue = Mapper<HomeDataModel>().mapArray(JSONObject: responseData)
{
self.homeScreenData = homeScreenDataValue
}
}
return
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
vc.homeScreenData = homeScreenData
vc.indexTagValue = indexPath.item
self.navigationController?.pushViewController(vc, animated: true)
}
Second View Controller:-
var homeScreenData = [HomeDataModel]()
var indexTagValue = 0
extension HomeScreenDetailViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return homeScreenData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell : HomeDataOtherCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "testCollectionViewCell", for: indexPath as IndexPath) as! testCollectionViewCell
cell.nameLabel.text = homeScreenData[indexPath.item].name
if let image = homeScreenData[indexPath.item].user_image {
if image.contains("https://") {
cell.userImageView.sd_setImage(with: URL(string: image ), placeholderImage: UIImage(named: "userIcon"))
} else {
let userImage = ImageURL + image
// userImageView.image = UIImage(named: userImage )
let urlString = userImage.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
cell.userImageView.sd_setImage(with: URL(string: urlString ?? ""), placeholderImage: UIImage(named: "userIcon"))
}
} else {
cell.userImageView.image = UIImage(named: "userIcon")
}
return cell
}
ImageURL in my app is
let ImageURL = "http://test/public/images/
It is recommended to pass the data model so that it can reduce a lot of unnecessary code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellid = "testCellID"
var cell = tableView.dequeueReusableCell(withIdentifier: cellid)
if cell==nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid)
}
let hero: Hero
hero = heroes[indexPath.row] as! Hero
cell?.textLabel?.text = hero.name
let url = URL(string: hero.imageUrl ?? "")
let data = try! Data(contentsOf: url!)
cell?.imageView?.image = UIImage(data: data)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let hero = heroes[indexPath.row] as! Hero
let heroesDetails = HeroesDetailsViewController()
heroesDetails.hero = hero
self.navigationController?.pushViewController(heroesDetails, animated: true)
}
class HeroesDetailsViewController: UIViewController {
#IBOutlet weak var detailsImg: UIImageView!
var hero: Hero!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: hero.imageUrl ?? "")
let data = try! Data(contentsOf: url!)
self.detailsImg?.image = UIImage(data: data)
}
}

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

Load/Download image from SDWebimage and display in Custom tableView cell imageView

i already parsed other values but how will i show image to imageView i m already using SdWebImage in Swift.I want to show that in Bottom cell "detail" Below is my code
import UIKit
import SystemConfiguration
import MBProgressHUD
public struct Section {
var arrayDataTop: String
var arrayTerms: String
var qrImage:String
var collapsed: Bool
public init( arrayDataTop: String,qrImage: String ,arrayTerms: String, collapsed: Bool = false) {
self.arrayDataTop = arrayDataTop
self.qrImage = qrImage
self.arrayTerms = arrayTerms
self.collapsed = collapsed
}
}
class CollapsibleViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableViewCollapsible:UITableView!
#IBOutlet weak var listImage:UIImageView!
var nodatastr:String = "No Deal Found."
var dealIDCollapsible : String?
var dealDictCollapsible = [String: AnyObject]()
var parentNavigationController: UINavigationController?
private var loadingView:MBProgressHUD?
var sectionDataObj = [Section]()
override func viewDidLoad() {
super.viewDidLoad()
if (!self.isInternetAvailable()){
self.alertMessageShow(title: "No Internet Connection", message: "Make sure your device is connected to the internet.")
}
else{
if self.loadingView == nil {
self.loadingView = MBProgressHUD.showAdded(to: self.view, animated: true)
}
tableViewCollapsible.estimatedRowHeight = 100.0
tableViewCollapsible.layoutIfNeeded()
tableViewCollapsible.updateConstraintsIfNeeded()
tableViewCollapsible.tableFooterView = UIView()
self.listImageFetch()
dealFetchParticularListing()
}
}
func dealFetchParticularListing(){
let prs = [
"listing_id":dealIDCollapsible,//dealIDCollapsible,
"Deal_fetch_listing": "1" as String
]
Service.CreateDeal(prs as [String : AnyObject]?, onCompletion: { result in
let json = result as? NSDictionary
if let data = json as? [String:Any]{
if let err = data["status"] as? String, err == "success"{
if let data = data["result"] as? [Any]{
//
//fill your data in that local Section obj
//
var sectionDataObj = [Section]()
for sectionObj in data{
if let sectionObjVal = sectionObj as? [String:Any]{
if let qrcode = sectionObjVal["qrcode"] as? String{
if let tnc = sectionObjVal["tnc"] as? String{
if let deal_title = sectionObjVal["deal_title"] as? String{
let sectionValue = Section(arrayDataTop: deal_title, qrImage: qrcode, arrayTerms: tnc)
// access main objects/UIelement on main thread ONLY
sectionDataObj.append(sectionValue)
}
}
}
}
}
DispatchQueue.main.async { () -> Void in
self.sectionDataObj.removeAll()
//
//assign ur data in main sampleData(Section obj) then reload tableView with that data.
//
self.sectionDataObj = sectionDataObj
self.tableViewCollapsible.reloadData()
self.loadingView?.hide(true)
}
}
}
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Header
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData
cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop
return cell
}
// Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData
cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms
// here i want to show image
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension//320.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
let collapsed = !sectionDataObj[indexPath.section].collapsed
// Toggle collapse
sectionDataObj[indexPath.section].collapsed = collapsed
self.tableViewCollapsible.reloadSections([indexPath.section], with: .automatic)
}
}
}
class MyCellData:UITableViewCell{
#IBOutlet weak var lblDealTitle: UILabel!
#IBOutlet weak var dealimage: UIImageView!
#IBOutlet weak var lblTerm: UILabel!
#IBOutlet weak var qrCodeImage: UIImageView!
}
Plz help me with this.thanks in advance.All things are working properly i am able to see other details.Help will be appreciated.Plz help me i m struggling with this issue.
update ur tableView cellForRowAt like so to show an image or ur cell from ur sectionDataObj
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Header
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyCellData
cell.lblDealTitle.text = sectionDataObj[indexPath.section].arrayDataTop
return cell
}
// Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! MyCellData
cell.lblTerm.text = sectionDataObj[indexPath.section].arrayTerms
let imgUrl = sectionDataObj[indexPath.section]. qrImage
cell.qrCodeImage.sd_setImage(with: URL(string:imgUrl), completed: nil)
return cell
}

Resources