认为没有在Swift工作

时间:2017-06-09 22:23:20

标签: ios arrays swift segue uistoryboardsegue

我正在尝试根据您单击的tableview单元格将数组的某个部分传递给另一个视图控制器。因此,当我点击第三个单元格时,它会将数组数据从第三个单元格发送到下一个屏幕。此数据是array,称为“待办事项”。当我尝试在下一个屏幕中接收数据时,没有数据。

代码:

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"

1 个答案:

答案 0 :(得分:3)

我怀疑你错过了点击单元格时会调用的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]
        }
    }
}