如何将我的数据从uitableview显示到uicollectionview?

时间:2016-08-14 00:58:39

标签: json swift uitableview uicollectionview uicollectionviewcell

我有一些非常有效的uitableview代码。这是代码。

import UIKit
import Alamofire
import ObjectMapper
import SwiftyJSON
import FirebaseAuth
import FirebaseStorage

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
//    @IBOutlet weak var symbolLbl: UILabel!
//    @IBOutlet weak var BidLbl: UILabel!

    var NumberofRows = 0
        let stockURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22+GRPN+SIRI+TVIX+EVOK+ZNGA+EPRS+TKAI+EBIO+DELT+SQNM+ALIM+ODP+ASTI+GBSN+FATE+BLDP+ETRM+GALE+VSTM+BIND+GEVO+DRAM+AMDA+BIOD+VNR+GLUU+AXAS+INFI+BLDP+SGYP+HLIT+ZIOP+XGTI+CIDM+CPLP+ORIG+DRRX+MNKD+GLBS+GERN+IMGN+IMMU+GLBS+GERN+IMGN+IMMU+GLBL+REXX+VIP+NETE+EXTR+CLNE+EBIO+ULTR+AAPL+TSLA+%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"
    //var StockArray = [String]()
    var BidArray = [Double]()
    var ChangeArray = [Double]()

    struct combinedStock {
        var symbol: String = ""
        var bid : Double = 0.0
        var change: Double = 0.0



    }
    var stockArray = [combinedStock]()




    @IBOutlet weak var tableView: UITableView!


//    @IBOutlet weak var StockSymbolLbl: UILabel!
//    @IBOutlet weak var BidSymbolLbl: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        getJSON()
        automaticallyAdjustsScrollViewInsets = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.registerNib(UINib(nibName: "StockHome", bundle: NSBundle.mainBundle()),forCellReuseIdentifier: "stockHome")
        tableView.rowHeight = 60
//        StockSymbolLbl.text = ""
//        BidSymbolLbl.text = ""


        }

    @IBAction func logout(sender: AnyObject) {
        let actionSheetController = UIAlertController(title: "Please Selecet", message: "Option to select", preferredStyle: UIAlertControllerStyle.ActionSheet)
        let cancelActionButton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (action) in
            print("Cancel")
        }
        actionSheetController.addAction(cancelActionButton)

        let profileActionButton = UIAlertAction(title: "Profile", style: UIAlertActionStyle.Default) { (action) in
            let profileVC = self.storyboard?.instantiateViewControllerWithIdentifier("profileViewConrtoller") as! ProfileTableViewController
            self.navigationController?.pushViewController(profileVC, animated: true)
        }
        actionSheetController.addAction(profileActionButton)
        let logoutAction = UIAlertAction(title: "Log Out", style: UIAlertActionStyle.Default) { (action) in
            print("log out")
            self.logoutDidTapped()
    }
        actionSheetController.addAction(logoutAction)

        self.presentViewController(actionSheetController, animated: true, completion: nil)
    }

    func logoutDidTapped() {
        DataService.dataService.logout()
    }

    func getJSON(){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        let url = NSURL(string: self.stockURL)
        let request = NSURLRequest(URL: url!)
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

            if error == nil {

                let swiftyJSON = JSON(data: data!)
                let Symbol: String? = swiftyJSON["query"]["results"]["quote"][0]["symbol"].stringValue
                let bid: String? = swiftyJSON["query"]["results"]["quote"][0]["Bid"].stringValue
                let change: String? = swiftyJSON["query"]["results"]["quote"][0]["Change"].stringValue
                print(change!)
                print(Symbol!)
                print(bid!)
                dispatch_async(dispatch_get_main_queue()) {
//                self.StockSymbolLbl.text? = "\(Symbol!)"
//                self.BidSymbolLbl.text? = "\(bid!)"
                    self.NumberofRows = swiftyJSON["query"]["results"]["quote"].count

                    for i in 0...self.NumberofRows {
                        var stockcount = 0
                        stockcount += i
                        let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
                        let Bid = swiftyJSON["query"]["results"]["quote"][stockcount]["Bid"].doubleValue
                        let Change = swiftyJSON["query"]["results"]["quote"][stockcount]["Change"].doubleValue
                        let homestocks = combinedStock(symbol: Stock, bid: Bid, change: Change)
//                        self.StockArray.append(Stock)
//                        print(Stock)
//                        self.BidArray.append(Bid)
//                        print(Bid)
//                        self.ChangeArray.append(Change)
//                        p
                        print(Change)
                        self.stockArray.append(homestocks)
                    }
                    self.stockArray = self.stockArray.sort({
                    return $0.change > $1.change
                    })

                    self.tableView.reloadData()
                }



            }else{
                print("There was an error")
            }

        }
        task.resume()
    }

}
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return NumberofRows
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: StockHome = tableView.dequeueReusableCellWithIdentifier("stockHome", forIndexPath: indexPath) as! StockHome

        if stockArray.count != 0{

            cell.symbolLbl?.text = stockArray[indexPath.row].symbol
            let bid = stockArray[indexPath.row].bid
            let changeRate = stockArray[indexPath.row].change
            cell.bidLbl?.text = "\(bid)" + " USD "
            cell.changeLbl?.text = "\(changeRate)" + " %"

        }

        print(self.stockArray)

        return cell
    }
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        switch stockArray[indexPath.row].change {
        case let x where x < 0.0:
            cell.backgroundColor = UIColor(red: 255.0/255.0, green: 59.0/255.0, blue: 48.0/255.0, alpha: 1.0)
        case let x where x > 0.0:
            cell.backgroundColor = UIColor(red: 76.0/255.0, green: 217.0/255.0, blue: 100.0/255.0, alpha: 1.0)
        case let x:
            cell.backgroundColor = UIColor(red: 44.0/255.0, green: 186.0/255.0, blue: 231.0/255.0, alpha: 1.0)
        }
        cell.textLabel!.textColor = UIColor.whiteColor()

        }


}

我正在尝试将视图从tableview更改为集合视图。我这样做了,但没有显示任何内容。在我将背景改为白色之前,我受到了黑屏的欢迎。这是我的集合视图的代码

import UIKit
import Alamofire
import ObjectMapper
import SwiftyJSON
import FirebaseAuth
import FirebaseStorage

class StockViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var NumberofRows = 0
    let stockURL = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22+GRPN+SIRI+TVIX+EVOK+ZNGA+EPRS+TKAI+EBIO+DELT+SQNM+ALIM+ODP+ASTI+GBSN+FATE+BLDP+ETRM+GALE+VSTM+BIND+GEVO+DRAM+AMDA+BIOD+VNR+GLUU+AXAS+INFI+BLDP+SGYP+HLIT+ZIOP+XGTI+CIDM+CPLP+ORIG+DRRX+MNKD+GLBS+GERN+IMGN+IMMU+GLBS+GERN+IMGN+IMMU+GLBL+REXX+VIP+NETE+EXTR+CLNE+EBIO+ULTR+AAPL+TSLA+%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json"

    var BidArray = [Double]()
    var ChangeArray = [Double]()

    struct combinedStock {
        var symbol: String = ""
        var bid : Double = 0.0
        var change: Double = 0.0

    }
    var stockArray = [combinedStock]()

    @IBOutlet weak var collectionview: UICollectionView!


    override func viewDidLoad() {
        super.viewDidLoad()
        automaticallyAdjustsScrollViewInsets = false
        collectionview.dataSource = self
        collectionview.delegate = self

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func getJSON(){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let url = NSURL(string: self.stockURL)
            let request = NSURLRequest(URL: url!)
            let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
            let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

                if error == nil {

                    let swiftyJSON = JSON(data: data!)
                    let Symbol: String? = swiftyJSON["query"]["results"]["quote"][0]["symbol"].stringValue
                    let bid: String? = swiftyJSON["query"]["results"]["quote"][0]["Bid"].stringValue
                    let change: String? = swiftyJSON["query"]["results"]["quote"][0]["Change"].stringValue
                    print(change!)
                    print(Symbol!)
                    print(bid!)
                    dispatch_async(dispatch_get_main_queue()) {
                        //                self.StockSymbolLbl.text? = "\(Symbol!)"
                        //                self.BidSymbolLbl.text? = "\(bid!)"
                        self.NumberofRows = swiftyJSON["query"]["results"]["quote"].count

                        for i in 0...self.NumberofRows {
                            var stockcount = 0
                            stockcount += i
                            let Stock = swiftyJSON["query"]["results"]["quote"][stockcount]["symbol"].stringValue
                            let Bid = swiftyJSON["query"]["results"]["quote"][stockcount]["Bid"].doubleValue
                            let Change = swiftyJSON["query"]["results"]["quote"][stockcount]["Change"].doubleValue
                            let homestocks = combinedStock(symbol: Stock, bid: Bid, change: Change)
                            //                        self.StockArray.append(Stock)
                            //                        print(Stock)
                            //                        self.BidArray.append(Bid)
                            //                        print(Bid)
                            //                        self.ChangeArray.append(Change)
                            //                        p
                            print(Change)
                            self.stockArray.append(homestocks)
                        }
                        self.stockArray = self.stockArray.sort({
                            return $0.change > $1.change
                        })

                        self.collectionview.reloadData()
                    }



                }else{
                    print("There was an error")
                }

            }
            task.resume()
        }

    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return NumberofRows
    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionview.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! homeCollectionViewCell
        if stockArray.count != 0{
            cell.symbolLbl?.text = self.stockArray[indexPath.item].symbol
            let bid = stockArray[indexPath.item].change
            let changeRate = stockArray[indexPath.item].change
            cell.bidLbl?.text = "\(bid)" + " USD "
            cell.percentLbl?.text = "\(changeRate)" + " %"

        }
        print(self.stockArray)
        return cell
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("You selected cell #\(indexPath.row)!")
    }

}

你可以说它们非常相似。我很想知道我错过了什么或做错了什么。谢谢。

P.S。这是uicollectionviewcell的代码

import UIKit

class homeCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var symbolLbl: UILabel!
    @IBOutlet weak var percentLbl: UILabel!
    @IBOutlet weak var bidLbl: UILabel!

}

谢谢。

0 个答案:

没有答案