ios - Segue 不适用于 Swift

标签 ios arrays swift segue uistoryboardsegue

我正在尝试根据您单击的表格 View 单元格将数组的特定部分传递给另一个 View Controller 。因此,例如,当我单击第三个单元格时,它会将数组数据从第三个单元格发送到下一个屏幕。此数据是一个名为“todos”的数组。当我尝试在下一个屏幕中接收数据时,没有数据。

代码:

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "EditTodo" {
        print("it is")
        var vc = segue.destination as! ViewController
        // var indexPath = tableView.indexPathForCell(sender as UITableViewCell)
        var indexPath = tableView.indexPathForSelectedRow
        if let index = indexPath {
            vc.todo = todos[index.row]
        }
    }
}

我不确定它是否正在被调用,或者是什么。标识符是正确的,我不确定还能做什么。 (当我运行它时,打印函数没有被调用,但我什至不确定它是否应该被调用)。

下面是带有表格的“发送数据”页面的整页代码:

import UIKit
var todos: [TodoModel] = []
var filteredTodos: [TodoModel] = []

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate {

@IBOutlet weak var tableView: UITableView!



override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
    print("i think it worked...")

    let defaults = UserDefaults.standard
    if todos.count > 0 {
        // Save what we have
        let data = NSKeyedArchiver.archivedData(withRootObject: todos)
        defaults.set(data, forKey: "TDDATA")
        defaults.synchronize()
        print("saved \(todos.count)")
    } else if let storedTodoData = defaults.data(forKey: "TDDATA"),
        let storedTodos = NSKeyedUnarchiver.unarchiveObject(with: storedTodoData) as? [TodoModel] {
        // There was stored data! Use it!
        todos = storedTodos
        print("Used \(todos.count) stored todos")

        tableView.reloadData()
        self.tableView.tableFooterView = UIView()
    }
   //print([todos.first])
    print("Here?: \(todos.first?.title)")
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override var prefersStatusBarHidden: Bool {
    return true
}
/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == searchDisplayController?.searchResultsTableView {
        return filteredTodos.count
    }
    else {
        return todos.count
    }
}

// Display the cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Must use 'self' here because searchResultsTableView needs to reuse the same cell in self.tableView
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "todoCell")! as UITableViewCell
    var todo : TodoModel

    if tableView == searchDisplayController?.searchResultsTableView {
        todo = filteredTodos[indexPath.row] as TodoModel
    }
    else {
        todo = todos[indexPath.row] as TodoModel
    }

    //var image = cell.viewWithTag(101) as! UIImageView
    var title = cell.viewWithTag(102) as! UILabel
    var date = cell.viewWithTag(103) as! UILabel




    //image.image = todo.image

    // image = UIImageView(image: newImage)

    // if image.image == nil{
    //    print("nilish")
    //     image = UIImageView(image: UIImage(named: "EmptyProfile.png"))
    // }


    // image.image = todo.image
    // if image.image == nil{
    //     print("pic is nil")
    //     image.image = UIImage(named: "CopyEmptyProfilePic.jpg")
    //  }



    title.text = todo.title
    date.text = "\(NSDate())"




    let locale = NSLocale.current
    let dateFormat = DateFormatter.dateFormat(fromTemplate: "yyyy-MM-dd", options:0, locale:locale)

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat


    return cell

}

// MARK - UITableViewDelegate
// Delete the cell
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete {
        todos.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
        let defaults = UserDefaults.standard
        if todos.count >= 0 {
            // Save what we have
            let data = NSKeyedArchiver.archivedData(withRootObject: todos)
            defaults.set(data, forKey: "TDDATA")
            defaults.synchronize()
            print("saved \(todos.count)")
        } else if let storedTodoData = defaults.data(forKey: "TDDATA"),
            let storedTodos = NSKeyedUnarchiver.unarchiveObject(with: storedTodoData) as? [TodoModel] {
            // There was stored data! Use it!
            todos = storedTodos
            print("Used \(todos.count) stored todos")
        }

        tableView.reloadData()
    }
}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 80
}

// Edit mode
override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)
    tableView.setEditing(editing, animated: true)
}

// Move the cell
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return self.isEditing
}

// func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
//  let todo = todos.removeAtIndex(sourceIndexPath.row)
//todos.insert(todo, atIndex: destinationIndexPath.row)
//   }

// MARK - UISearchDisplayDelegate
// Search the Cell
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String?) -> Bool {
    //filteredTodos = todos.filter({( todo: TodoModel) -> Bool in
    //    let stringMatch = todo.title.rangeOfString(searchString)
    //    return stringMatch != nil
    //})

    // Same as below
    filteredTodos = todos.filter(){$0.title.range(of: searchString!)
        != nil}
    return true
}

// MARK - Storyboard stuff
// Unwind
@IBAction func close(segue: UIStoryboardSegue) {
    print("closed!")
    tableView.reloadData()
}

// Segue
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "EditTodo" {
        print("it is")
        var vc = segue.destination as! ViewController
        // var indexPath = tableView.indexPathForCell(sender as UITableViewCell)
        var indexPath = tableView.indexPathForSelectedRow
        if let index = indexPath {
            vc.todo = todos[index.row]
        }
    }
  }

}

我如何在接收屏幕的viewDidLoad中接收数据:

nameOfDocTF.delegate = self

nameOfDocTF.text = todo?.title
outputTextView.attributedText = todo?.desc
print(todo?.title)
//prints "nil"

最佳答案

我怀疑您缺少 didSelectRowAt 函数,当您单击一个单元格时将调用该函数,您需要从那里调用您的 prepareForSegue。实现以下功能并尝试:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "EditTodo", sender: indexPath.row)
}

然后将您的 prepareForSegue 函数替换为以下内容:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "EditTodo" {
        let vc = segue.destination as! ViewController
        if let index = sender as? Int {
            vc.todo = todos[index]
        }
    }
}

关于ios - Segue 不适用于 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467448/

相关文章:

ios - Swift 2 - 定时 Action 间隔一秒?

ios - 目标中缺少 SDK - iphoneos5.0

ios - 在没有 CATiledLayer 的情况下在 Scrollview 容器中呈现巨大的网格?

c++ - C++类中的静态动态二维数组

ios - 如何使用mailcore2获取邮件的发件人个人资料图片

ios - 图像未绑定(bind)到 UIImageView

ios - 从 iOS 应用程序中编码 mjpeg 文件

java - 二维数组帮助

c - 将文件中的单词存储到 C 中的数组中

ios - Swift Firebase Ios 用户定义的子值