gpt4 book ai didi

ios - UICollectionView 数组索引超出范围

转载 作者:行者123 更新时间:2023-11-28 09:20:59 26 4
gpt4 key购买 nike

我正在尝试在 Swift 中创建一个非常基本的 Collection View Controller ,它允许我列出一些数字,当我点击其中一个时,它会将我带到一个详细信息页面,该页面只是(在标签中)简单地说明了你的数字敲击。

Storyboard:我的 Storyboard有一个导航 Controller 作为根和一个加载的 Collection View Controller 。这包含一个单元格,其标识符为单元格。此单元格有一个按钮,用作详细信息页面的 segue。我已将数据源指定为指向自身(控件单击到 View Controller 的行以建立数据源)并且我已将 segue 唯一标识为 showDetail。

当我加载该应用程序时,它会显示我的按钮 7 次,但是当我单击其中任何一个按钮时,我会在下面的行中得到一个超出范围的索引:

这是我的代码:

import Foundation
import UIKit


class WeekCollectionView : UICollectionViewController
{
override func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int
{
return 7
}

override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!

{
let cell: ShiftCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as ShiftCell
return cell;
}

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)

{
if (segue.identifier == "showDetail") {
**//CRASHES ON THIS LINE BELOW FOR THE ARRAY [0]**
let indexPaths: NSArray = self.collectionView.indexPathsForSelectedItems()[0] as NSArray
let destinationViewController = segue.destinationViewController as DetailViewController
//var someNumber = images[indexPath.row]
destinationViewController.mySpecialID = 1 //replace this with someNumber, always set 1 for now as a test
}
}
}

我的单元格类(上图)很简单:

class ShiftCell: UICollectionViewCell { 
init(frame: CGRect) {
super.init(frame: frame)
}

init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}

}

我真的不确定我做错了什么 - 也许我的 Storyboard 中需要发生其他事情?我按照 apple 的教程(在 objective-c 中)进行了完美的操作,如果我没记错的话,所有代码方面的内容都是相同的!

我真的被困在这里,如果有人能指出我正确的方向,非常感谢! :)

最佳答案

您遇到此崩溃是因为没有选定的项目。您在单元格顶部有一个按钮,阻止触摸到达单元格以实际选择它。您将不得不想出一种不同的方法来识别每个按钮所代表的行。一个常见的模式是使用按钮的 tag 属性。这可以存储任意整数以帮助您识别 View 。

因此,在 collectionView:cellForItemAtIndexPath 中,您应该将按钮的标签设置为当前索引:

override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
let cell: ShiftCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as ShiftCell
cell.myButton.tag = indexPath.item
return cell;
}

然后我相信 segue 的 sender 将是按钮。您可以从中获取索引:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
{
if (segue.identifier == "showDetail") {
var possibleIndex : Int?
if let button = sender as? UIButton {
possibleIndex = button.tag
}

if let index = possibleIndex {
// ...
}
}
}

注意:我不确定发件人会是按钮,因为我通常通过代码而不是 Storyboard来做事。如果发送者不是按钮,你总是可以用“老式的方式”来做,并将按钮连接到 Storyboard 中的 View Controller 上的一个方法,而不是使用 segue。然后,您可以在代码中创建新 Controller 并根据需要显示它。

关于ios - UICollectionView 数组索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com