Swift: Показать данные из tableView в другой ViewController (JSON, Alamorife, AlamofireImage) - PullRequest
0 голосов
/ 26 июня 2018

Я пытаюсь сделать приложение, в котором данные были получены из JSON.

На рисунке ниже вы можете увидеть проект: Проект
Если мы нажмем нафотография открывает страницу с подробностями.Проблема в том, что я не знаю, как подобрать данные, показанные на странице сведений.Пожалуйста, помогите мне.Вот код

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

}

Также вы можете увидеть код DetailsViewController:

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

Ответы [ 2 ]

0 голосов
/ 26 июня 2018
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]()
}
0 голосов
/ 26 июня 2018

Вы можете легко передать значение из табличного представления в подробное представление, используя следующий код:

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!
    }
...