数组索引超出范围Query和CollectionCell

时间:2015-12-23 11:08:50

标签: ios swift parse-platform uicollectionview

出于某种原因,我无法弄清楚我做错了什么:

我正在尝试在我的Parse数据库中查询URL,将它们放入一个名为facebookPics的数组中。后来我想在我的cellForRowAtIndexPath中查看,

if facebookPics.count < indexPath.row

然后在我的CollectionViewCells中加载数据。 =&GT;我每次都有6个。

代码:

 override func viewWillAppear(animated: Bool) {
    let infoQuery = PFUser.query()
    infoQuery?.whereKey("objectId", equalTo: objectID!)

    infoQuery?.findObjectsInBackgroundWithBlock({ (results, error) -> Void in
        if error != nil{

            let userMessage = error!.localizedDescription
            let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)
            let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
            myAlert.addAction(okAction)
            self.presentViewController(myAlert, animated: true, completion: nil)

            return
        }
        else if results != nil{

            for result in results! {


                let imageFile = result["firstImage"] as! PFFile
                // Image muss ja erstmal gedownloaded werden.
                imageFile.getDataInBackgroundWithBlock {
                    (imageData: NSData?, error: NSError?) -> Void in

                    if error != nil {
                        let userMessage = error!.localizedDescription
                        let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)
                        let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
                        myAlert.addAction(okAction)
                        self.presentViewController(myAlert, animated: true, completion: nil)

                        return

                    } else {
                        if let data = imageData {

                            self.miniImage.image = UIImage(data: data)

                        }

                    }

                }
                // Jetzt der firstname, birthday und abouttext
                var profilText = result["first_name"] as! String
                self.nameAgeLabel.text = profilText

                if let geburtstag = result["birthday"] as? String {

                    let calendar = NSCalendar.currentCalendar()
                    let currentDate = NSDate()
                    let birthdayFormatter = NSDateFormatter()
                    birthdayFormatter.dateFormat = "MM/DD/YYYY"
                    let birthday = birthdayFormatter.dateFromString(geburtstag)



                    let ageComponents = calendar.components(.Year,
                        fromDate: birthday!,
                        toDate: currentDate,
                        options: [])


                    let age = ageComponents.year


                    profilText += ", " + String(age)
                    self.nameAgeLabel.text = profilText


                }


                if let hashtags = result["hashtags"] as? String {

                    self.hashtagText.text = hashtags

                }

                if let images = result["images"] as? [String] {



                    for image in images {

                        let nsURL = NSURL(string: image)
                        var urls:[NSURL] = [NSURL]()
                        urls.append(nsURL!)
                        self.facebookPics = urls

                    }

                    print(self.facebookPics)


                }






            }

            self.mainCollectionView.reloadData()


        }
    })

}


override func viewDidLoad() {
    super.viewDidLoad()


    // Do any additional setup after loading the view.
    let image : UIImage = UIImage(named: "Überschrift.png")!
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 80, height: 30))
    imageView.contentMode = .ScaleAspectFit
    imageView.image = image
    self.navigationItem.titleView = imageView

    // Navigation Controller Top soll Durchsichtig sein
    self.navigationController?.navigationBar.opaque = true

    miniImage.layer.borderWidth = 0.5
    miniImage.layer.masksToBounds = false
    miniImage.layer.borderColor = UIColor.darkGrayColor().CGColor
    miniImage.layer.cornerRadius = miniImage.frame.width/2
    miniImage.clipsToBounds = true

    hashtagText.layer.borderWidth = 1.5
    hashtagText.layer.borderColor = UIColor.darkTextColor().CGColor
    hashtagText.layer.cornerRadius = 7







    // Suche starten um folgende Infos zu bekommen [Profilbild, firstname, abouttext, andere Bilder adressen.]





}

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




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

// Alle images.count => returnen! max 6



return 6



}
//FEHLERHAFTE FUNKTION



func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let collectionCell:SettingsCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as! SettingsCollectionViewCell

    collectionView.backgroundColor = UIColor.whiteColor()


    collectionCell.backgroundColor = UIColor.whiteColor()
    collectionCell.frame.size.width = 80
    collectionCell.frame.size.height = 80
    collectionCell.layer.borderWidth = 1
    collectionCell.layer.borderColor = UIColor.darkGrayColor().CGColor
    collectionCell.layer.cornerRadius = collectionCell.frame.size.width/2




    if facebookPics.count < indexPath.row{

        if let data = NSData(contentsOfURL: facebookPics[indexPath.row]) {
            let image = UIImage(data: data)
            collectionCell.collectionViewImage.image = image
        }
    }

    else {
        // Clear out the image on a recycled cell
        collectionCell.collectionViewImage = nil
    }


    let cellImage = collectionCell.collectionViewImage

    if cellImage == nil {

        self.counter = 1
        print("empty")
        collectionCell.collectionViewButton.center.x = 40
        collectionCell.collectionViewButton.center.y = 40
        collectionCell.collectionViewButton.setImage(UIImage(named: "check.png"), forState: UIControlState.Normal)



    }
    else {

        self.counter = 0
        print("hello")
        collectionCell.collectionViewButton.center.x = 60
        collectionCell.collectionViewButton.center.y = 60
        collectionCell.collectionViewButton.setImage(UIImage(named: "close-o.png"), forState: UIControlState.Normal)
        collectionCell.collectionViewButton.tintColor = UIColor.redColor()
    }







    return collectionCell
}

2 个答案:

答案 0 :(得分:1)

您必须反转if条件

如果您有0张图片,那么您当前的代码会进入if块,并尝试显示第3张,因为0&lt; 3评估为真。这与你想要的完全相反。更常见的是,当前且仅当索引完全超出范围时,您才会输入真分支。

正确的检查是:

if indexPath.row < facebookPics.count {
    // logic
}

答案 1 :(得分:0)

不要问我为什么,但这终于有效。

Backbone.history.navigate(this.model.get('user').url + '/' + this.model.id, {trigger: false, replace: true});