2016-05-03 5 views
1

Ich habe eine Sammlungsansicht und sie hat ungefähr 5 Zellen. Welches bin ich von api holen, um die Zellendaten in der Sammlungsansicht zu zeigen. Wenn Benutzer auf eine Zelle klicken, werden die entsprechenden Daten in der folgenden Tabelle angezeigt.So zeigen Sie die ersten Daten in der Tabellenansicht an, während Daten von der API abgerufen werden

Jetzt funktioniert alles gut. Aber wenn ich erstmal meine Ansicht lade. In meiner Tabellenansicht werden keine Daten angezeigt ... Was ich meine ist? Standardmäßig müssen die ersten Daten der Collection-View-Zelle in der Tabellenansicht angezeigt werden. Aber ich bekomme oder zeige nicht.

Wenn ich nur auf eine Zelle klicke, kann ich die Daten in meiner Tabellenansicht sehen. Aber was ich brauche, ist - Standardmäßig muss die erste Zelle der Sammlungsansicht in der Tabellenansicht angezeigt werden, wenn ich diesen Bildschirm öffne.

Wie geht das?

Hier ist mein Code:

@IBOutlet var BTCollectionView: UICollectionView! 

    @IBOutlet var DLTableView: UITableView! 

    var BTdata = [BTData]() 

    var Dealsdata = [DealsData]() 
override func viewDidLoad() 
    { 
     super.viewDidLoad() 
// nib for custom cell (table view) 
     let nib = UINib(nibName:"DealsListTableCell", bundle: nil) 
     DLTableView.registerNib(nib, forCellReuseIdentifier: "DealCell") 

     ListBusinessTypes() 
} 
    // Values from Api for Business Types 
    func ListBusinessTypes() 
    { 
     let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String 

     let headers = ["x-access-token": token] 

     let request = NSMutableURLRequest(URL: NSURL(string: "httpsome url")!, 
              cachePolicy: .UseProtocolCachePolicy, 
              timeoutInterval: 10.0) 
     request.HTTPMethod = "GET" 
     request.allHTTPHeaderFields = headers 

     let session = NSURLSession.sharedSession() 
     let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in 
      if (error != nil) 
      { 
       print(error) 

       let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert) 

       // add an action (button) 
       ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 

       // show the alert 
       self.presentViewController(ErrorAlert, animated: true, completion: nil) 
      } 
      else 
      { 
       if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject> 
       { 
        let success = json["success"] as? Int 

        if(success == 1) 
        { 
         if let typeValues = json["data"] as? [NSDictionary] 
         { 
          dispatch_async(dispatch_get_main_queue(),{ 

           for item in typeValues 
           { 
            self.BTdata.append(BTData(json:item)) 

            self.BTCollectionView.reloadData() 
           } 
          }) 
         } 
        } 
        else 
        { 
         let message = json["message"] as? String 

         print(message) 

         let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert) 

         // add an action (button) 
         ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 

         // show the alert 
         self.presentViewController(ServerAlert, animated: true, completion: nil) 
        } 
       } 
      } 
     }) 

     dataTask.resume() 
    } 

// Mark : Collection View Delegate and Datasource(Business Type) 
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    { 
     return BTdata.count 
    } 

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
    { 
     let cell: DDLCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("HCollectionCell", forIndexPath: indexPath) as! DDLCollectionCell 
     cell.BTName.text = BTdata[indexPath.row].BTNames 
     return cell 
    } 

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
    { 
     ListDeals(BTdata[indexPath.row].BTIds!) 
    } 


func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    { 
     return 1 
    } 

    // number of rows 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    { 
     return Dealsdata.count 
    } 

    // calling each cell based on tap and users (premium/non premium) 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    { 
     let tabcell = tableView.dequeueReusableCellWithIdentifier("DealCell") as! DealsListTableCell 

     tabcell.DealName.text = Dealsdata[indexPath.row].DealNames 

     if let imgURL = NSURL(string: Dealsdata[indexPath.row].DealImageUrls!) 
     { 
      let request: NSURLRequest = NSURLRequest(URL: imgURL) 

      let session = NSURLSession.sharedSession() 

      let Imgtask = session.dataTaskWithRequest(request) 
      { 
       (data, response, error) -> Void in 

       if (error == nil && data != nil) 
       { 
        func display_image() 
        { 
         tabcell.DealImage.image = UIImage(data: data!) 
        } 
        dispatch_async(dispatch_get_main_queue(), display_image) 
       } 
      } 
      Imgtask.resume() 
     } 
     else 
     { 
      tabcell.DealImage.image = UIImage(named: "FBLogo") 
     } 

     let formatter = NSDateFormatter() 
     formatter.locale = NSLocale(localeIdentifier: "en_US") 
     formatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSSxxx" 

     let date = formatter.dateFromString(Dealsdata[indexPath.row].DealExpiry!) 

     let dateFormatter = NSDateFormatter() 
     dateFormatter.dateStyle = .MediumStyle 
     dateFormatter.timeStyle = .NoStyle 
     dateFormatter.locale = NSLocale(localeIdentifier: "en_US") 
     let FormattedDate = dateFormatter.stringFromDate(date!) 

     tabcell.RegPriceLabel.text = String(Dealsdata[indexPath.row].DealRegularPrice!) 

     tabcell.SalePriceLabel.text = String(Dealsdata[indexPath.row].DealSalePrice!) 

     tabcell.DealExpiryDate.text = "Expiries on : "+FormattedDate 

     let BArrayValue:NSDictionary = Dealsdata[indexPath.row].DealBusinessDetails! 

     let BName = BArrayValue.valueForKey("business_name") as! String 

     let BImage = BArrayValue.valueForKey("images") as! NSArray 

     let BMainImage = BImage[0] as! NSDictionary 

     let FinalImage = BMainImage.valueForKey("url") as! String 

     if let imgURL2 = NSURL(string: FinalImage) 
     { 
      let request: NSURLRequest = NSURLRequest(URL: imgURL2) 

      let session = NSURLSession.sharedSession() 

      let Imgtask = session.dataTaskWithRequest(request) 
      { 
       (data, response, error) -> Void in 

       if (error == nil && data != nil) 
       { 
        func display_image() 
        { 
         tabcell.DealBusinessImage.image = UIImage(data: data!) 
        } 
        dispatch_async(dispatch_get_main_queue(), display_image) 
       } 
      } 
      Imgtask.resume() 
     } 
     else 
     { 
      tabcell.DealBusinessImage.image = UIImage(named: "FBLogo") 
     } 


     let BLatLng = Dealsdata[indexPath.row].DealCoordinates 

     let UserLocation = CLLocation(latitude: NewCurrentLatitude, longitude: NewCurrentLongitude) 

     let BusinessLocation = CLLocation(latitude: BLatLng![0] as! Double, longitude: BLatLng![1] as! Double) 

     let distance = UserLocation.distanceFromLocation(BusinessLocation)/1000 

     tabcell.DealBusinessNameWithDistance.text = BName+" - "+String(format: "%.1f",distance)+" Km" 

     return tabcell 
    } 

Bitte helfen Sie mir. Vielen Dank!

Does ich brauche irgend etwas in folgenden Zeile zu ändern:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) 
    { 
     ListDeals(BTdata[indexPath.row].BTIds!) 
    } 

Antwort

0

Try ListDeals(BTdata[0].BTIds!) aufzurufen, nachdem Sie die Daten von Ihrem API geladen.

... 

if let typeValues = json["data"] as? [NSDictionary] 
        { 
         dispatch_async(dispatch_get_main_queue(),{ 

          for item in typeValues 
          { 
           self.BTdata.append(BTData(json:item)) 

           self.BTCollectionView.reloadData() 
          } 
          ListDeals(BTdata[0].BTIds!) 
         }) 
        } 

... 
+0

Ja, wenn ich meinen Bildschirm ersten Daten ist jetzt neues Problem showing.But laden occur.That ist - Es gibt 5 cell.Only ersten beiden Zell data.other Zellen sind nicht haben data.But mit, wenn ich drücken meine dritte Zelle. Meine zweiten Zellendaten sind immer noch in der Tabellenansicht. Dieses Problem ist auch für meine 3,4, 5 Zellen. – user5513630

Verwandte Themen