У меня возникла проблема с изменением элементов пользовательского интерфейса в моих TrophyCollectionViewCell
.UICollectionViewCell не редактируется в didSelectItemAtIndexPath
Когда я изменяю их с помощью метода cellForItemAtIndexPath
, это нормально и работает как ожидалось. Однако, когда я изменяю их в методе didSelectItemAtIndexPath
, никаких изменений не происходит.
Например, следующее в didSelectItemAtIndexPath
:
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as TrophyCollectionViewCell
cell.trophyImageView.hidden = true
cell.reloadInputViews()
Это не делает trophyImageView
скрыто. Он ничего не делает.
Редактирование базовой модели данных делает работу, однако (это в didSelectItemAtIndexPath
а):
self.placeHolderArray[indexPath.row] = ""
self.collectionViewController.collectionView!.reloadData()
Это создает тот же эффект, я желаю только я редактирую модель данных collectionView
«s установить неправильный образ актив для указанных trophyImageView
.
Примечание:
placeHolderArray
успешно подаетcollectionView
имен файлов изображений, которые устанавливаются вUIImage
изcell.trophyImageView
в методеcellForIndexPath
.
Так почему же я не могу правильно отредактировать ячейку trophyImageView
?
Вот мой полный код.
import UIKit
class CollectionHolderViewController: MainPageContentViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionViewController = UICollectionViewController()
var placeHolderArray = ["derplol_trophy", "medallion_of_courage", "derp_trophy", "herp_trophy", "jordy_trophy", "cotton_trophy", "weird_trophy", "rash_trophy"]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionViewController = self.storyboard!.instantiateViewControllerWithIdentifier("TrophyRoom") as UICollectionViewController
self.collectionViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.addChildViewController(collectionViewController)
self.view.addSubview(collectionViewController.view)
self.collectionViewController.didMoveToParentViewController(self)
self.collectionViewController.collectionView!.dataSource = self
self.collectionViewController.collectionView!.delegate = self
//self.flowLayout!.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as TrophyCollectionViewCell
cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight //to fix Apple bug.
cell.trophyImageView.image = UIImage(named: placeHolderArray[indexPath.row]) //THIS WORKS.
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return placeHolderArray.count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as TrophyCollectionViewCell
self.collectionViewController.collectionView!.scrollEnabled = false // disable scrolling so view won't move
let innerOffset = collectionView.contentOffset as CGPoint // offset of content view due to scrolling
let attributes = self.collectionViewController.collectionView!.layoutAttributesForItemAtIndexPath(indexPath) as UICollectionViewLayoutAttributes!
let cellRect = attributes.frame // frame of cell in contentView
var imageView = UIImageView(frame: CGRectMake(cellRect.origin.x + innerOffset.x, cellRect.origin.y + innerOffset.y, cellRect.size.width, cellRect.size.height))
imageView.image = UIImage(named: placeHolderArray[indexPath.row]) //change.
imageView.contentMode = UIViewContentMode.ScaleAspectFit
var trophyCase = UIImageView(frame: CGRectMake(cellRect.origin.x + innerOffset.x, cellRect.origin.y + innerOffset.y, cellRect.size.width, cellRect.size.height))
trophyCase.image = UIImage(named: "trophy_case")
trophyCase.contentMode = UIViewContentMode.ScaleAspectFit
self.view.addSubview(trophyCase)
self.view.addSubview(imageView)
cell.trophyImageView.hidden = true //THIS DOES NOT WORK.
cell.reloadInputViews()
//self.placeHolderArray[indexPath.row] = ""
//self.collectionViewController.collectionView!.reloadData()
UIView.animateWithDuration(0.5, animations: {
imageView.frame = self.view.frame
trophyCase.frame = self.view.frame
}, completion: {
(value: Bool) in
})
}
}
Класс моей ячейки, который правильно установлен в построителе интерфейса.
import UIKit
class TrophyCollectionViewCell: UICollectionViewCell {
@IBOutlet var trophyImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
Что так странно, что мой UICollectionView
может модифицировать trophyImageView
в cellForIndexPath
, но не в didSelectAtIndexPath
.
Вы не должны изменять ячейку в didSelectItemAtIndexPath в любом случае - если вы это сделаете, любое изменение, которое вы сделаете, будет отображаться при другой indexPath, когда ячейка будет повторно использована. – rdelmar
Это правда, хотя мне любопытно, почему это происходит (почему нет прав на trophyImageView, которые происходят правильно?). Имейте в виду, что я фактически отключил scrollView, когда ячейка выбрана, поэтому она не будет загружать дополнительные ячейки. – CaptainCOOLGUY