ios - 解析 Koloda 库上的数据 - 无法在 View 中显示

标签 ios iphone xcode swift parse-platform

有人可以告诉我我做错了什么吗? 可能很多,因为我是新手,但期待解决这个问题!

我正在使用 Koloda 库 ( https://github.com/Yalantis/Koloda/tree/networking_example ) 将对象数组提取到卡片中,这样每张卡片都会从我的数据库中获取一行。我已经看到了 Alamofire 的网络示例,并尝试了我自己的代码来使用相同的示例实现 Parse。它正在从 Parse 获取对象,但我无法将它们显示到卡片中。奇怪,实际上我没有错误,控制台显示“成功检索 5 个对象”,但这只是 loadData() 函数。

我要用 nib 在那里显示很多文本!

我主要想达到什么目的: 我有提供标签的 (MyView.xib, MyView.swift)。 (我想要的是从数组中检索文本到 xib 的标签中)

我正在检索对象,但未能成功将它们显示到卡片中:

Successfully retrieved 5 posts.
Optional("EvUICgRQ6E")
Optional("5kC0FLKQON")
Optional("1Uyxb2M1Et")
Optional("aeJpRCG7Qn")
Optional("GDmGh3IULm")

一些错误: 如果我返回“numberOfCards”——我收到此错误:

fatal error: Array index out of range
(lldb) 

如果我返回:“return UInt (self.data.count)” 我没有收到任何错误,但卡片根本没有显示。

我有点新手,但指出了一个好的方向我就能完成它。

这是我的 ViewController.swift 代码:

    //
//  ViewController.swift
//  TinderCardsSwift
//
//  Created by Eugene Andreyev on 4/23/15.
//  Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//

import UIKit
import Koloda
import pop
import Parse
import ParseUI

private var numberOfCards: UInt = 5

class ViewController: UIViewController, KolodaViewDataSource, KolodaViewDelegate {

    @IBOutlet weak var kolodaView: KolodaView!

    @IBOutlet weak var menuLeft: UIBarButtonItem!
    @IBOutlet weak var searchRight: UIBarButtonItem!

    var cardsCollection: [MyView] = []

    var labelText3 = ""
    var labelText4 = ""

    var currentObject:PFObject?

    override func viewDidLoad() {
        super.viewDidLoad()

        kolodaView.dataSource = self
        kolodaView.delegate = self

        menuLeft.target = self.revealViewController()
        menuLeft.action = Selector("revealToggle:")

        searchRight.target = self.revealViewController()
        searchRight.action = Selector("rightRevealToggle:")

        self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal

        loadData()

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

    }


    //MARK: Geting Data From Parse and displaying 5 posts with a print result - WORKING
    func loadData (){

        if (!cardsCollection.isEmpty) {
            self.kolodaView.reloadData()
            return
        }

        let query = PFQuery(className:"Countries")
        query.orderByAscending("nameEnglish")
        query.findObjectsInBackgroundWithBlock {
            (objects:[PFObject]?, error:NSError?) -> Void in
            if error == nil {
                // The find succeeded.
                print("Successfully retrieved \(objects!.count) posts.")
                // Do something with the found objects
                if let objects = objects {
                    for object in objects {
                        let view = NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)[0] as! MyView
                        view.label1.text = object["nameEnglish"] as? String
                        view.label2.text = object["capital"] as? String
                        self.cardsCollection += [view]
                        print(object.objectId)

                    }
                }
            } else {
                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
        self.kolodaView.reloadData()
        return
    }

    /*func printData () {

        let dataView = NSBundle.mainBundle().loadNibNamed("MyView",
            owner: self, options: nil)[0] as? MyView
        if let nameEnglish = object?["nameEnglish"] as? String {

            let lbl2 = dataView?.label1 as UILabel!
            lbl2!.text = nameEnglish




        }

        //return printData()
    }*/
    @IBAction func logOut4(sender: AnyObject) {

        // Send a request to log out a user
        PFUser.logOut()

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let viewController:UIViewController = UIStoryboard(name: "SlideMain", bundle: nil).instantiateViewControllerWithIdentifier("Login_Platform")
            self.presentViewController(viewController, animated: true, completion: nil)


        })

    }

    override func viewWillAppear(animated: Bool) {

        if (PFUser.currentUser() == nil) {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                let viewController:UIViewController = UIStoryboard(name: "SlideMain", bundle: nil).instantiateViewControllerWithIdentifier("Login_Platform")
                self.presentViewController(viewController, animated: true, completion: nil)



            })
        }

    }


    //MARK: IBActions
    @IBAction func leftButtonTapped() {
        kolodaView?.swipe(SwipeResultDirection.Left)
    }

    @IBAction func rightButtonTapped() {
        kolodaView?.swipe(SwipeResultDirection.Right)
    }

    @IBAction func undoButtonTapped() {
        kolodaView?.revertAction()
    }

    //MARK: KolodaViewDataSource
    func kolodaNumberOfCards(koloda: KolodaView) -> UInt {
       return numberOfCards
        //return UInt (self.data.count)
        //return UInt(cardsCollection.count)

    }

    func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView {
        //return UIImageView(image: UIImage(named: "Card_like_\(index + 1)"))
        return (NSBundle.mainBundle().loadNibNamed("MyView",
        owner: self, options: nil)[0] as? MyView)!
        //let view = cardsCollection[Int(index)]
        //return view


       /* let dataView = NSBundle.mainBundle().loadNibNamed("MyView",
            owner: self, options: nil)[0] as? MyView
        let parseData = data[Int(index)]
        dataView?.label1?.text = parseData.labelText
        dataView?.label2?.text = parseData.label2Text

        return dataView!*/


    }
    func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView? {
        return NSBundle.mainBundle().loadNibNamed("OverlayView",
            owner: self, options: nil)[0] as? OverlayView
    }

    //MARK: KolodaViewDelegate

    func kolodaDidSwipedCardAtIndex(koloda: KolodaView, index: UInt, direction: SwipeResultDirection) {
        //Example: loading more cards
        if index >= 3 {
            numberOfCards = 5
            kolodaView.reloadData()
        }
    }

    func kolodaDidRunOutOfCards(koloda: KolodaView) {
        //Example: reloading
        kolodaView.resetCurrentCardNumber()
        loadData()
    }

    func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt) {
        UIApplication.sharedApplication().openURL(NSURL(string: "http://yalantis.com/")!)
    }

    func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool {
        return true
    }

    func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool {
        return true
    }

    func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool {
        return true
    }

    func kolodaBackgroundCardAnimation(koloda: KolodaView) -> POPPropertyAnimation? {
        return nil
    }

}

This is MyView.swift (where I defined everything)

  //
//  MyView.swift
//
//
//  Created by Viorel Petrisor on 12/29/15.
//  Copyright © 2015 Viorel Petrisor. All rights reserved.
//

import UIKit

class MyView: UIView {

    @IBOutlet var label1: UILabel!
    @IBOutlet var label2: UILabel!
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

}

MyView 有它自己的 Nib 。 还要在我的项目中放置一些图片:

KolodaView in my Main StoryBoard

有没有人知道如何让它工作?我已经苦苦挣扎了 10 天,但仍然无法正常工作。

非常感谢您的帮助和提示!

UPDATE: I am now using this function for loadData()

func loadData (){

        if (!cardsCollection.isEmpty) {
            self.kolodaView.reloadData()
            return
        }

        let query = PFQuery(className:"Countries")
        query.orderByAscending("nameEnglish")
        query.findObjectsInBackgroundWithBlock {
            (objects:[PFObject]?, error:NSError?) -> Void in
            if error == nil {
                // The find succeeded.
                print("Successfully retrieved \(objects!.count) posts.")
                // Do something with the found objects
                if let objects = objects {
                    for object in objects {
                        let view = NSBundle.mainBundle().loadNibNamed("MyView", owner: self, options: nil)[0] as! MyView
                        view.label1.text = object["nameEnglish"] as? String
                        view.label2.text = object["capital"] as? String
                        self.cardsCollection += [view]
                        print(object.objectId)

                    }
                }
            } else {
                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
        self.kolodaView.reloadData()
        return
    }

WITH this variable

var cardsCollection: [MyView] = []

最佳答案

我有一个类似的问题,卡没有获取数据。显然,这是我如何调用 Bundle 的问题。更正下面的 Swift 3.0 代码。

func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {

    let bundle = Bundle(for: MyView.self) // This gets the correct bundle for your class, as sometimes you might have many bundles.
    let nib = UINib(nibName: String(describing: MyView.self), bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! MyView

    return view
}

关于ios - 解析 Koloda 库上的数据 - 无法在 View 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34486221/

相关文章:

ios - 以编程方式创建 UIToolbar

ios - 在 UICollectionView 选择上选择 UITableView

当用户截取屏幕截图/照片时,ios 执行方法

iphone - Xcode 创建中的 plist

ios - 适用于Xcode 5的iOS 8模拟器

ios - 仅将圆角半径设置为 UIView/UIButton 的特定一侧

iphone - 控制音频的声音

ios - 打开 Watch 应用程序以配对 Apple Watch 的 URL 方案

iphone - 将滚动条添加到 ViewController( Storyboard)

ios - Xcode7 不记录崩溃报告