将图像数组从Json文件传递到ImageView控制器

时间:2019-02-27 02:48:27

标签: json swift tableview searchbar

我正在尝试使用搜索控制器进行tableview,根据用户在搜索栏tableview中选择的选项,将图像数组从Json文件传递到新的viewcontroller。我为我的应用程序创建了一个搜索栏,该显示栏将显示该应用程序中的所有信息,以便用户可以轻松选择想要查看的图片。通过使用表格视图可以正常工作,当用户选择一行时,它将带有相关图片的变量发送到另一个屏幕上的图片视图。

由于我拥有很多选择,所以我创建了一个Json文件。我对它进行了编码,它将根据用户在搜索栏中键入的内容返回选项。我的问题是我无法将图像数组从.json文件传递到图像视图控制器。它将显示视图控制器,但“数组”图像视图为空白,因为未传递图片数组。下面是我的代码,想知道是否有人有任何想法可以将我指向正确的方向,或者告诉我我做错了什么。

搜索条形码:

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)

}

}

其他使用的代码:

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

1 个答案:

答案 0 :(得分:0)

在目标控制器中

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 ?? [])")

    }
}

在源控制器TableView委托中

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)
    }

更新2-将图像显示为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)
    }