George Copeland George Copeland - 2 years ago 149
Swift Question

Swipe left and right between Core Data with a label

I hope you can help.
There is a label and when any user swipe on it. It will make a call to core data and show values on label. Data will depend upon gesture. If its left/right data will be different on each time. Below is the code that i have written. Please suggest whether its correct or not?

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

Answer Source

I think you need to modify your handleSwipes and outputData function.

You outputData should only fetch all the data from CD in viewDidload. Once you have the data source you can fetch item from source and populate your helloLabel based on index.

@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
    }

And:

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

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download