ios - 如何在 Swift 中根据上一个 Controller 中选定的单元格值加载数组

标签 ios arrays swift

我正在尝试构建类似于笔记应用程序工作方式的东西,但是当您选择笔记而不是文本时,您会得到一个包含从数组加载的单元格的 collectionView

假设我有两个相互连接的 viewController。 firstViewController 有一个 collectionView,其中加载了注释名称,选择注释后,它将转到 secondViewController,后者将加载该注释的数组.

我很难理解其中的逻辑...我是使用 NSUserDefaults 并为每个注释创建一个 objectForKey 还是为每个注释创建一个新数组。 我将如何存储这些?

firstViewController

class MainViewController: UIViewController, UICollectionViewDelegate {

 var objects = Array<NSDate>()


 @IBAction func insertNewObject(sender: AnyObject) {

    objects.insert(NSDate(), atIndex: 0)
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    collectionView.insertItemsAtIndexPaths([indexPath])
}

 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

storyboard?.instantiateViewControllerWithIdentifier("secondtView") as! SecondViewController

//How do I proceed here? 

}
}

第二个ViewController

var myArray:[[AnyObject]] = []
class SecondViewController: UIViewController, UICollectionViewDelegate {


override func viewDidLoad() {
    super.viewDidLoad()
    if (NSUserDefaults.standardUserDefaults().objectForKey("myArray") != nil) {
    myArray = NSUserDefaults.standardUserDefaults().objectForKey("myArray") as! [[AnyObject]]
    }
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      myArray.count
}



 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> CollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell 
 cell.cellLabel.text = myArray[indexPath.row][0] as? String
 return cell 
}

最佳答案

我没有足够的时间写出实际的解决方案,因此我只是向您提供解决您的问题所需的步骤,然后您就可以从那里开始解决。

首先,我会使用核心数据。拥有一个注释实体,其中包含注释名称、注释消息、时间以及您认为重要的其他属性。

数据结构就位后,每当用户点击 Collection View 中的 View 时,都会将该值保存为 current_selected 或 NSUserDefaults 中的其他值。

然后转到第二个 View Controller 并加载当前选择的值。然后在 coredata 数据结构中查找相关信息。

here is a link on using core data

and here is one on using NSUserDefaults ,希望这有帮助

关于ios - 如何在 Swift 中根据上一个 Controller 中选定的单元格值加载数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31094065/

相关文章:

ios - 创建应用程序无法下载的ios链接

ios 5 - 在 Storyboard上反射(reflect)的代码

arrays - 在 FORTRAN-77 中传递二维数组的子数组

ios - Swift Firebase 下载 map 注释上的注释图像单击

swift - 具有相同名称的多个函数

iphone - 如何正确处理 iOS 中的互联网连接不可用?

objective-c - 调用 [alert show] 后 UIAlertView 未立即显示

python - 对特征值和特征向量进行排序

python - numpy矢量化方法来计算整数数组中的非零位

ios - 使用 SwiftUI 将列表滚动到底部