У меня есть следующий Segue в моей раскадровке, который подключается к ViewController, вид корня которого является UICollectionView
не может динамически изменять начальные содержимое UICollectionView
После этого урока: https://www.youtube.com/watch?v=L9cZrAbxN1E
Я создал аналогичную настройку UICollectionViewController
с пользовательским источником данных. Основное различие между его кодом и моей собственностью заключается в том, что он немедленно устанавливает dataArray объектов, которые сопоставляются один к одному в каждой ячейке collectionView, в viewDidLoad
, тогда как я захватываю их от асинхронного обратного вызова и установки результирующих объектов в моем источнике данных массив для моих ячеек просмотра.
Проблема в том, что ничего не добавлено к моему представлению после того, как я последую за сеансом, который я показываю в начале. Главный ViewController вида, изображенный на Раскадке, имеет тип FeedController
, поэтому я знаю, что это не так. Я чувствую, что это потому, что мой contentSize не установлен правильно, возможно. Это просто странно, потому что человек в видео никогда явно, насколько мне известно, не устанавливает размер своей коллекцииView.
import UIKit
let cellId = "cellId"
class FeedController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var recipes = [BrowsableRecipe]()
var recipeIndex = 1
var pageSize = 10
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Homepage"
collectionView?.alwaysBounceVertical = true
collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
collectionView?.registerClass(RecipeCell.self, forCellWithReuseIdentifier: cellId)
ServerMessenger.sharedInstance.getRecipesForHomePage(recipeIndex, pageSize: pageSize){
responseObject, error in
if let data = responseObject{
self.recipes = data
print(self.recipes)
}
}
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recipes.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let recipeCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! RecipeCell
print("cellForItem called")
recipeCell.recipe = recipes[indexPath.item]
return recipeCell
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
collectionView?.collectionViewLayout.invalidateLayout()
}
}
class RecipeCell: UICollectionViewCell {
var recipe: BrowsableRecipe? {
didSet {
if let name = recipe?.recipeName {
let attributedText = NSMutableAttributedString(string: name, attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(14)])
nameLabel.textColor = UIColor.blackColor()
print("in did set")
nameLabel.attributedText = attributedText
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let nameLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 2
return label
}()
func setupViews() {
backgroundColor = UIColor.blueColor()
addSubview(nameLabel)
addConstraintsWithFormat("V:|-12-[v0]", views: nameLabel)
}
}
extension UIColor {
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
}
}
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerate() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
}
Причина, почему нет контента отображается в этом collectionView
я не уверен, что непосредственно связано с тем, что cellForItemAtIndexPath
никогда не называется (я тестировал с заявлениями для печати)
Любая помощь приветствуется.
ориентировочные, здесь есть проект, который я использовал в качестве отправной точки https://github.com/purelyswift/facebook_feed_dynamic_cell_content
UPDATE:
Я пытался делать это с reloadItemsAtIndexPaths
в моем асинхронным обратного вызова:
и Я получаю
reason: 'attempt to delete item 9 from section 0 which only contains 0 items before the update'
, который предложил мне сначала добавить что-то в раздел 0. так я стараюсь:
self.collectionView!.insertItemsAtIndexPaths(myArrayOfIndexPaths)
И я получаю:
reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: