我查了很多例子并尝试合并,但都没有成功。在我的CollectionView(已放置在ViewController中)中,我想选择一个单元格并将单元格图像推送到另一个ViewController。图像已放置在字典数组中。我不确定,我应该如何编辑我的prepareForSegue或我的func collectionView ... didSelectItemAtIndexPath。此外,任何与您的代码一起使用的详细说明都会有所帮助,因为我还在学习swift及其语法。
以下是我认为您需要的所有信息,但如果您需要更多信息,请告诉我们:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowToStory") {
var story = sender as! UICollectionViewCell, indexPath = collectionView.indexPathForCell(story)
}
}
private func initStoryImages() {
var storyArchives = [StoryImages]()
let inputFile = NSBundle.mainBundle().pathForResource("StoryArchive", ofType: "plist")
let inputDataArray = NSArray(contentsOfFile: inputFile!)
for inputItem in inputDataArray as! [Dictionary<String, String>] {
let storyImage = StoryImages(dataDictionary: inputItem)
storyArchives.append(storyImage)
}
storyImages = storyArchives
}
ADDITIONAL CLASS:CollectionViewCell类
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellImage: UIImageView!
func setStoryImage(item:StoryImages){
cellImage.image = UIImage(named:item.itemImage)
}
}
ADDITIONAL CLASS:UIViewController
class StoryView: UIViewController{
@IBOutlet weak var ImageToStory: UIImageView!
var story: StoryImages?
override func viewDidLoad() {
super.viewDidLoad()
ImageToStory.image = UIImage(named: (story?.itemImage)!)
}
}
其他类:StoryImages
class StoryImages{
var itemImage: String
init(dataDictionary:Dictionary <String,String>) {
itemImage = dataDictionary["ItemImage"]!
}
class func newStoryImage(dataDictionary:Dictionary<String,String>) -> StoryImages {
return StoryImages(dataDictionary: dataDictionary)
}
}
}
答案 0 :(得分:1)
首先传递selectedItem
didSelectItemAtIndexPath
的indexPath
现在以prepareForSegue
方法传递图像
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowToStory") {
let cell = sender as! UICollectionViewCell //Change UICollectionViewCell with CustomCell name if you are using CustomCell
let indexPath = self.collectionView?.indexPathForCell(cell)
let story = storyImages[indexPath.row]
let destVC = segue.destinationViewController as! StoryView
destVC.selectedStory = story
}
}
现在在您要传递图片的StoryImages
中声明一个StoryView
种类型的对象,并在viewDidLoad
中使用该对象来分配图片
var selectedStory: StoryImages?
override func viewDidLoad() {
super.viewDidLoad()
ImageToStory.image = selectedStory.itemImage // or use NSData if it contain url string
}