使用标签在Core Data之间左右滑动

时间:2017-10-03 09:05:26

标签: swift core-data swift3

我希望你能提供帮助。 当有任何用户在其上滑动时,有一个标签。它将调用核心数据并在标签上显示值。数据取决于手势。如果每次左/右数据不同。下面是我写的代码。请提出是否正确?

class ViewController: UIViewController {

    var helloArray = [Tasks]()
    var currentArrayIndex = 0

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var helloLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.handleSwipes(sender:)))

        let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.handleSwipes(sender:)))

        leftSwipe.direction = .left
        rightSwipe.direction = .right

        view.addGestureRecognizer(leftSwipe)
        view.addGestureRecognizer(rightSwipe)

        ouputData()
    }

    @objc func handleSwipes(sender: UISwipeGestureRecognizer) {

        if sender.direction == .left {
            currentArrayIndex = (currentArrayIndex + 1) % 3
        }
    }

    func ouputData() {
        do {
            helloArray = try context.fetch(Tasks.fetchRequest())
            for each in helloArray {
                helloLabel.text = each.name
            }
        } catch {
        }
        appDelegate.saveContext()
    }

    @IBAction func btnPressed(_ sender: Any) {
        let infoTasks = Tasks(context: context)
        infoTasks.name = textField.text

        appDelegate.saveContext()

        do {
            try context.save()
        } catch {
            print("Error")
        }
        textField.text = ""
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您需要修改handleSwipes和outputData函数。

你的outputData应该只从viewDidload中获取CD中的所有数据。 获得数据源后,您可以从源中获取项目并根据索引填充helloLabel。

@objc func handleSwipes(sender: UISwipeGestureRecognizer) {

        if sender.direction == .left {
            currentArrayIndex = (currentArrayIndex + 1) % 3
        } else if sender.direction == .right {
            currentArrayIndex = (currentArrayIndex - 1) % 3
        }
        helloLabel.text =  helloArray[currentArrayIndex].name
    }

func ouputData() {
        do {
            helloArray = try context.fetch(Tasks.fetchRequest())
        } catch {
        }
        appDelegate.saveContext()
    }

希望它有所帮助。