我已经研究过这个问题,我几乎可以肯定我的代码是正确的,但显然有些问题。我有两个控制器。一个有TableView,另一个是带标签的视图控制器。我希望将用户选择的tableview单元格中的单元格文本标签的值发送到第二个视图控制器。很简单。这是我的控制器:
import UIKit
import CoreData
class FavoritesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var selectedFavorite = ""
var specifiedFavorite:String!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var passages = [NSManagedObject]()
//This code creates the number of cells equal the number of items in the object
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return passages.count
}
// The code below displays the passage reference as the cell title
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// This creates the cell for the table. The dequeueReusableCell option ensures the table is scrollable
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
// this creates a variable for the record defined at the index that is numbered by the indexPath.row.
let favorite = passages[indexPath.row]
// We then find the value of the key we want to set for the cell label value
cell.textLabel!.text = favorite.value(forKey: "reference") as? String
return cell
}
// This code detects the cell selected and captures a variable that is passed in the segue
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as UITableViewCell!
selectedFavorite = (selectedCell?.textLabel?.text)!
print("The text in the selected cell is \(selectedFavorite)")
performSegue(withIdentifier: "toFavoritesDetailsViewController", sender: nil)
print("Segue performed")
}
//This code is the segue that passes the variable values to the next view
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toFavoritesDetailsViewController" {
let favoritesDetailsViewController = segue.destination as! FavoritesDetailsViewController
favoritesDetailsViewController.specifiedFavorite = selectedFavorite
print("The variable for selectedFavorite prior to segue is: \(selectedFavorite)")
print("The variable for favoritesDetailsViewController.specifiedFavorite prior to segue is: \(favoritesDetailsViewController.specifiedFavorite)")
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//This code loads the Core Data Entity into the view
// this is working as evidenced by the tableview being populated with data
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Passages")
//
do {
let results = try managedContext.fetch(fetchRequest)
passages = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error)")
}
}
}
这是我的第二个控制器的代码,名为FavoritesDetailsViewController:
import UIKit
import CoreData
class FavoritesDetailsViewController: UIViewController {
@IBOutlet weak var referenceLabel: UILabel!
@IBOutlet weak var passageText: UITextView!
var specifiedFavorite : String = ""
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
referenceLabel.text? = specifiedFavorite
print("The viewDidLoad")
// SMC LEFT OFF HERE
// Can't get selectedFavorite to load from previous controller
print("The Value of variable specifiedFavorite sent from segue is: \(specifiedFavorite)")
print(specifiedFavorite)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Passages")
request.predicate = NSPredicate(format: "reference = %@", specifiedFavorite)
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
print("fetch request was successful")
if results.count > 0 {
for result in results as! [NSManagedObject] {
// print("We got results!")
if let returnedText = result.value(forKey: "passagetext") as? String {
print("This is the value of returnedText: \(returnedText)")
passageText.text? = returnedText
print("This is the text of the selectedFavorite after segue is: \(passageText)")
}
}
}
} catch {
print("Couldn't fetch results")
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("The viewDidLoad")
print("The Value of variable specifiedFavorite sent from segue is: \(specifiedFavorite)")
print(specifiedFavorite)
}
}
当我运行应用程序时,日志表明变量“specifiedFavorite”的值是在segue之前设置的。
The variable for selectedFavorite prior to segue is:
The variable for favoritesDetailsViewController.specifiedFavorite prior to segue is:
The viewDidLoad
The Value of variable specifiedFavorite sent from segue is:
The text in the selected cell is John 3:16
The variable for selectedFavorite prior to segue is: John 3:16
The variable for favoritesDetailsViewController.specifiedFavorite prior to segue is: John 3:16
2016-12-10 12:43:54.624 Logos to Mind[4036:770173] <UIView: 0x7ff0bf918010; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x600000421fa0>>'s window is not equal to <Logos_to_Mind.FavoritesDetailsViewController: 0x7ff0bf9047f0>'s view's window!
Segue performed
The FavoritesDetailsViewController viewDidLoad
The Value of variable specifiedFavorite sent from segue is:
fetch request was successful
请注意日志消息: 从segue发送的变量specifiedFavorite的值是:
是空的。
这是我的问题。我没有看到我的代码中存在哪些错误未能在FavoritesDetailsViewController中设置“specifiedFavorite”变量。我在这里碰到了一堵砖墙。会很感激一些见解。
答案 0 :(得分:1)
您的segue是从原型单元连接的。不要为didSelectRowAt
而烦恼,因为它是在prepare(for:sender)
之后调用的。在prepare(for:sender:)
完成所有工作。 sender
是触发segue的单元格:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toFavoritesDetailsViewController" {
let favoritesDetailsViewController = segue.destination as! FavoritesDetailsViewController
if let selectedCell = sender as? UITableViewCell {
let selectedFavorite = (selectedCell.textLabel?.text)!
favoritesDetailsViewController.specifiedFavorite = selectedFavorite
print("The variable for selectedFavorite prior to segue is: \(selectedFavorite)")
print("The variable for favoritesDetailsViewController.specifiedFavorite prior to segue is: \(favoritesDetailsViewController.specifiedFavorite)")
}
}
}