-2

I'm Trying to have tableview with a search controller pass image Array from Json file to a new viewcontroller based on what option the user picks in search bar tableview. I have created a search bar for my App that displays will display all of the information in the app so the user can easily pick the pictures they want to see. That works normally by using a tableview, and when the user pick a row, it sends a variable with the associated pictures to an image view on the other screen.

Because of the amount of options I have, I created a Json file. I have it coded where it will return options based on what the user types into the search bar. My problem is that I am unable to pass the Image Array from the .json file to the image view controller. It will display the viewcontroller, but the "array" imageview is blank as no picture array is being passed. Below is my code and am wondering if anyone has any ideas that could point me in the right direction, or tell me what I am doing wrong.

Search Bar code:

import UIKit

class ProtocolCell: UITableViewCell {

@IBOutlet weak var pNameLabel: UILabel!

}

extension String {

func trimmed() -> String {

return self.trimmingCharacters(in: .whitespaces)

}

}

class SearchController: UIViewController, UISearchBarDelegate {

/// Search Bar

@IBOutlet weak var pSearchBar: UISearchBar!

/// Proto Array

fileprivate var myProtocols:[Protocols]?

/// Searhed Array

fileprivate var searchedProtocols:[Protocols]?

/// TableView

@IBOutlet weak var protocolsTV: UITableView!

/// Is Searching

fileprivate var isSearching:Bool=false

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

protocolsTV.tableFooterView=UIView()

pSearchBar.delegate=self

myProtocols=[Protocols]()

searchedProtocols=[Protocols]()

myProtocols?.removeAll()

searchedProtocols?.removeAll()

myProtocols=Functions.getAllProtocolsFromJson()

if protocolsTV.delegate == nil {

protocolsTV.delegate=self

protocolsTV.dataSource=self

}

protocolsTV.reloadData()

}

}

extension SearchController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return isSearching == false ? (myProtocols?.count ?? 0) : (searchedProtocols?.count ?? 0)

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "ProtocolCell") as! ProtocolCell

cell.pNameLabel.text=isSearching == false ? (myProtocols![indexPath.row].pName ?? "") : (searchedProtocols![indexPath.row].pName ?? "")

return cell

}

//EDIT TABLE FUNCTION HERE!!!!!//

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

print("Is Searching: \(isSearching) ImagesArray: \(isSearching==true ? (searchedProtocols?[indexPath.row].imagesName ?? []) : (myProtocols?[indexPath.row].imagesName ?? []))")

let Vc = self.storyboard?.instantiateViewController(withIdentifier: "imageViewController") as! imageViewController

let home = self.storyboard?.instantiateViewController(withIdentifier: "FIRST") as! ViewController

//switch indexPath.section

// {

// case 0:

if searchedProtocols?[indexPath.row].pName == "test" {

let arrayStorage = myProtocols?[indexPath.row].imagesName ?? []

Vc.passedArray = arrayStorage

print(arrayStorage)

print(myProtocols?[indexPath.row].imagesName ?? [])

self.navigationController?.pushViewController(Vc, animated: true)

}

else {

self.navigationController?.pushViewController(home, animated: true)

}

// break;

// default:

// self.navigationController?.pushViewController(home, animated: true)

// }

}

func updateSearchData(With searchText: String, In searchBar: UISearchBar) {

if searchText.trimmed().count == 0 {

isSearching=false

searchBar.setShowsCancelButton(false, animated: true)

} else {

isSearching=true

searchBar.setShowsCancelButton(true, animated: true)

}

if isSearching {

/// We Are Searching Sort Array

if searchedProtocols == nil { searchedProtocols=[Protocols]() }

searchedProtocols?.removeAll()

searchedProtocols=myProtocols!.filter({($0.pName ?? "").lowercased().contains(searchText.lowercased())})

/// Make Set So, Data isn't Repeated

searchedProtocols=Array(Set(searchedProtocols ?? []))

} else {

/// Searching is Stopped

searchedProtocols?.removeAll()

}

protocolsTV.reloadData()

}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

updateSearchData(With: searchText, In: searchBar)

}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

self.view.endEditing(true)

}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

searchBar.setShowsCancelButton(false, animated: true)

searchBar.text=nil

isSearching=false

searchedProtocols?.removeAll()

protocolsTV.reloadData()

self.view.endEditing(true)

}

}

Other Used Code:

class Protocols: NSObject {

var pName:String?

var imagesName:[UIImage]!

override init() {}

init(With Dict: [String:Any]) {

pName=Dict["name"] as? String ?? ""

imagesName=Dict["imagesArray"] as? [UIImage] ?? []

}

ImageViewController:

class imageViewController: UIViewController,GADBannerViewDelegate, UIGestureRecognizerDelegate, UIScrollViewDelegate {
    @IBOutlet weak var pageControl: UIPageControl!

    var bannerView: GADBannerView!

    var index = 0
    var mySelectedProtocol:Protocols?

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var myImageView: UIImageView!


    @IBAction func pictureSwipe(_ sender: Any) {

     let pictureString = self.passedArray[index]
    self.myImageView.image = pictureString
    index = (index < passedArray.count-1) ? index+1 : 0
    self.pageControl.numberOfPages = passedArray.count
    self.pageControl.currentPage = index
}

    @IBAction func pictureswipeback(_ sender: Any) {
        let pictureString = self.passedArray[index]
        self.myImageView.image = pictureString
        index = (passedArray.count-1)
        self.pageControl.numberOfPages = passedArray.count
        self.pageControl.currentPage = index

    }

    func configurePageControl() {
        self.pageControl.numberOfPages = passedArray.count
        self.pageControl.currentPage = 0
        self.pageControl.pageIndicatorTintColor = UIColor.white
        self.pageControl.currentPageIndicatorTintColor = UIColor.red
        self.view.addSubview(pageControl)
        if index == 1 {
            self.pageControl.currentPage = 1
        }
        func updateCurrentPageDisplay(){
            self.pageControl.numberOfPages = passedArray.count
        }
    }

    var passedImage : UIImage! = nil
    var passedArray : [UIImage]!


    override func viewDidLoad(){
        super.viewDidLoad()
        self.myImageView.image = passedArray.first
        configurePageControl()
        scrollView.delegate = self



    self.navigationController?.navigationBar.isHidden = false

        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 5.0
wcdean217
  • 237
  • 1
  • 2
  • 9

1 Answers1

0

In Destination Controller

class DestinationVC: UIViewController {

    var mySelectedProtocol:Protocols?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        if mySelectedProtocol == nil { self.navigationController?.popViewController(animated: true) }
        /// We have Data
        print("Img Array with Name ==> \(mySelectedProtocol?.imagesName ?? [])")

    }
}

In Source Controller TableView Delegate

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Is Searching: \(isSearching) ImagesArray: \(isSearching==true ? (searchedProtocols?[indexPath.row].imagesName ?? []) : (myProtocols?[indexPath.row].imagesName ?? []))")
        let vc:DestinationVC=mainStoryBoard.instantiateViewController(withIdentifier: "DestinationVC") as! DestinationVC
        vc.mySelectedProtocol=isSearching==true ? (searchedProtocols?[indexPath.row]) : (myProtocols?[indexPath.row])
        self.navigationController?.pushViewController(vc, animated: true)
    }

Update 2 - Show Images as PageViewController

private func addPageView() {
        myScrollView.backgroundColor=UIColor.clear
        myScrollView.isUserInteractionEnabled=true
        myScrollView.showsHorizontalScrollIndicator=false
        myScrollView.isPagingEnabled=true
        myScrollView.delegate=self
        myScrollView.bounces=false

        self.count=mySelectedProtocol!.imagesName!.count
        for i in 0..<self.count {
            ///Get Origin
            let xOrigin : CGFloat = CGFloat(i) * myScrollView.frame.size.width
            ///Create a imageView
            let imageView = UIImageView()
            imageView.frame = CGRect(x: xOrigin, y: 0, width: myScrollView.frame.size.width, height: myScrollView.frame.size.height)
            imageView.contentMode = .scaleAspectFit
            imageView.image=UIImage(named: mySelectedProtocol!.imagesName![i])
            myScrollView.addSubview(imageView)
        }
        setUpPageControl()
        ///Set Content Size to Show
        myScrollView.contentSize = CGSize(width: myScrollView.frame.size.width * CGFloat(self.count), height: myScrollView.frame.size.height)
    }
Jatin Garg
  • 206
  • 1
  • 12
Jatin Garg
  • 306
  • 1
  • 2
  • 16