swift - 在带有标签的核心数据之间左右滑动

标签 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 = ""
    }
}

最佳答案

我认为你需要修改你的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()
    }

希望有帮助。

关于swift - 在带有标签的核心数据之间左右滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46540954/

相关文章:

ios - 重新启动应用程序后显示放置图钉?

ios - Touch ID IOS 10 需要 10 - 15 秒才能响应

ios - 如何在 Swift 中保存从 UIImagePickerController 中选取的图像?

ios - 我想在 coredata 中存储 allowsCameraControl 的 pointOfView.position

ios - 字符串数组中不区分大小写的匹配搜索 swift 3

ios - cellForRowAtIndexPath 在源获取数据之前执行

iphone - 如何将预先存在的 sqlite 文件导入核心数据?

ios - RestKit - 到同一实体的关系映射创建无限循环

swift - 如何在 Swift 中向实体插入新数据?

ios - 当collectionview水平滚动时,如何确定选择了哪个tableView Cell