Swift 3中的UILongPressGestureRecognizer

时间:2017-01-06 10:22:24

标签: ios swift uilongpressgesturerecogni

我是Swift 3的新手,想要创建一个To-Do-List。但是在viewDidLoad中,由于UILongPressGestureRecognizer,应用程序总是崩溃。我在互联网上搜索,但我找不到有效的解决方案。

这是我的代码,每次都说"线程1:断点1.1"与UILongPressGestureRecognizer一致:

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

(lldb)

我该怎么办?

1 个答案:

答案 0 :(得分:0)

假设您已在项目的目标中添加了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