gpt4 book ai didi

ios - Swift 3 中的 UILongPressGestureRecognizer

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:10 25 4
gpt4 key购买 nike

我是 Swift 3 的新手,想创建一个小的待办事项列表。但是在 viewDidLoad 中,由于 UILongPressGestureRecognizer,App 总是崩溃。我在互联网上搜索,但没有找到可行的解决方案。

这是我的代码,每次它在与 UILongPressGestureRecognizer 的行中显示“线程 1:断点 1.1”时:

class ViewController: UIViewController, UITableViewDelegate {


@IBOutlet weak var newButton: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var editButton: UIButton!

var todoList = Todo.load(){
didSet{
Todo.save(todoList)
}
}


override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:)))
lpgr.minimumPressDuration = 1.2
tableView.addGestureRecognizer(lpgr)
}


func handleLongPress(_ gesture: UILongPressGestureRecognizer){
if gesture.state != .began { return }
let pt = gesture.location(in: tableView)
let path = tableView.indexPathForRow(at: pt)
if let row = (path as NSIndexPath?)?.row,
let cell = tableView.cellForRow(at: path!){
showPopup(sender: cell, mode: "edit", text: todoList[row], row: row)
}
}

这是 todo.txt 文件的代码:

struct Todo {
static func save(_ data: [String]){
if let url = docUrl(for: "todo.txt"){
do {
let str = data.joined(separator: "\n")
try str.write(to: url, atomically: true, encoding: .utf8)
} catch {
print(error)
}
}
}
static func load() -> [String] {
if let url = docUrl(for: "todo.txt"){
do{
let str = try String(contentsOf: url,
encoding: .utf8)
return str.characters
.split {$0 == "\n"}
.map { String($0)}
} catch {
print(error)
}
}
return []
}
private static func docUrl(for filename: String) -> URL? {
let urls = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)
if let docDir = urls.first {
return docDir.appendingPathComponent(filename)
}
return nil
}

这是我的错误报告:

 Error Domain=NSCocoaErrorDomain Code=260 "The file “todo.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/mkartds/Library/Developer/CoreSimulator/Devices/5D70E1CB-6D29-49E4-BCD1-316B5022F085/data/Containers/Data/Application/34869E75-E498-4674-B504-E7867935E3FE/Documents/todo.txt, NSUnderlyingError=0x61000004a830 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

(数据库)

我该怎么办?

最佳答案

假设您已经在项目的目标中添加了 todo.txt 文件。

尝试更新 docUrl 方法,

private static func docUrl() -> URL? {
let bundle = Bundle.main
let path = bundle.path(forResource: "todo", ofType: "txt")
let fileURL = URL(fileURLWithPath: path)
return fileURL
}

停用断点:

enter image description here

关于ios - Swift 3 中的 UILongPressGestureRecognizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com