希望能帮到你。 有一个标签,当任何用户在其上滑动时。它将调用核心数据并在标签上显示值。数据将取决于手势。如果它的左/右数据每次都会不同。下面是我写的代码。请大家指教,正确与否?
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/