当我点击NSCollectionViewItem时,我试图让我的数据从一个视图传递到下一个视图。单击某个项目时,我只想将一些数据传递到新视图,以获得每个项目的更“详细”视图。
我不断收到“致命错误:在打开Optional值时意外发现nil”。我觉得我错过了ProductDetail.swift文件中的关键步骤。该错误发生在我的prepare()方法中ViewController.swift的底部。关于如何为OS X执行此操作的过程与iOS完全不同,因此将非常感谢任何帮助。
ViewController.swift
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var colView: NSCollectionView!
var productCategories: [ProductCategory]?
var productsArray: [ProductModel]?
var detailLabel: test1?
override func viewWillAppear() {
super.viewWillAppear()
preferredContentSize = NSSize(width: 1025, height: 1200)
}
override func viewDidLoad() {
super.viewDidLoad()
getJSON()
}
func getJSON() {
let requestURL: NSURL = NSURL(string: "http://myurl.php")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers)
self.productsArray = [ProductModel]()
if let products = json as? [[String: Any]] {
for product in products {
let testproduct = ProductModel()
testproduct.product_name = product["product_name"] as? String
testproduct.product_price = product["product_price"] as? String
testproduct.product_image = product["product_image"] as? String
self.productsArray?.append(testproduct)
}
DispatchQueue.main.async(){
self.colView.reloadData()
}
}
}catch {
print("Error parsing the JSON: \(error)")
}
}
}
task.resume()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
extension ViewController: NSCollectionViewDataSource, NSCollectionViewDelegate{
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return productsArray?.count ?? 0
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "test1", for: indexPath) as! test1
item.buildProduct = productsArray?[indexPath.item]
return item
}
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
print("selected")
self.performSegue(withIdentifier: "showProductDetail", sender: self)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if (segue.identifier == "showProductDetail") {
if let detailVC = segue.destinationController as? ProductDetail {
detailVC.testLabel.stringValue = (detailLabel?.label.stringValue)!
}else{
detailLabel?.label.stringValue = "failed"
}
}
}
}
test1.swift
import Cocoa
class test1: NSCollectionViewItem {
@IBOutlet weak var label: NSTextField!
@IBOutlet weak var label2: NSTextField!
@IBOutlet weak var productImageView: NSImageView!
var productItem: ProductModel?
var buildProduct: ProductModel? {
didSet{
label.stringValue = (buildProduct?.product_name)!
label2.stringValue = (buildProduct?.product_price)!
setupAppIconImage()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
func setupAppIconImage() {
if let appIconImageURL = buildProduct?.product_image {
let url = NSURL(string: appIconImageURL)
URLSession.shared.dataTask(with: url! as URL,completionHandler:{(data, response, error) in
if error != nil {
print(error)
return
}
self.productImageView.image = NSImage(data: data!)
}).resume()
}
}
}
ProductDetail.swift
import Cocoa
class ProductDetail: NSViewController {
@IBOutlet weak var testLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
}
}
答案 0 :(得分:1)
我最终搞清楚了。它比我想象的要简单得多。我需要创建一个变量来保存传入的新数据。感谢Santosh的帮助和指导。
<强> ProductDetail.swift 强>
class ProductDetail: NSViewController {
@IBOutlet weak var testLabel: NSTextField!
var theBigPass = String()
override func viewDidLoad() {
super.viewDidLoad()
testLabel.stringValue = theBigPass
}
}
ViewController.swift Segue Methods
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
print("selected")
let selectedIndexPath = collectionView.selectionIndexPaths.first
let item = collectionView.item(at: selectedIndexPath!)
detailLabel = item as! test1?
self.performSegue(withIdentifier: "showProductDetail", sender: self)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if (segue.identifier == "showProductDetail") {
if let detailVC = segue.destinationController as? ProductDetail {
let passed = (detailLabel?.label.stringValue)!
detailVC.theBigPass = passed
}
}
}