UICollectionView sizeForItemAt IndexPath

Я пытаюсь установить размер для своей ячейки в соответствии с тем, что внутри, это мой код, и он падает, и я не могу найти сообщение об ошибке.

extension TimelineCollectionVC: UICollectionViewDelegateFlowLayout {



func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeline", for: indexPath) as? Timeline

    cell?.textView.translatesAutoresizingMaskIntoConstraints = true
    cell?.textView.sizeToFit()



    if cell?.containerView.subviews.count == 0 {
        cell?.containerHeight.constant = 1
    } else {
        cell?.containerHeight.constant = (cell?.containerView.subviews.first?.frame.size.height) ?? 80
    }

    let cellHeight = (cell?.upperView.bounds.height)! + (cell?.textView.bounds.height)! + (cell?.containerView.bounds.height)! + (cell?.lowerView.bounds.height)!


    return CGSize(width: 375, height: cellHeight)



}

}

Вы не должны использовать

extension TimelineCollectionVC: UICollectionViewDelegateFlowLayout {



func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeline", for: indexPath) as? Timeline

    cell?.textView.translatesAutoresizingMaskIntoConstraints = true
    cell?.textView.sizeToFit()



    if cell?.containerView.subviews.count == 0 {
        cell?.containerHeight.constant = 1
    } else {
        cell?.containerHeight.constant = (cell?.containerView.subviews.first?.frame.size.height) ?? 80
    }

    let cellHeight = (cell?.upperView.bounds.height)! + (cell?.textView.bounds.height)! + (cell?.containerView.bounds.height)! + (cell?.lowerView.bounds.height)!


    return CGSize(width: 375, height: cellHeight)



}
здесь. Это только для создания новых ячеек. В этом случае вы хотите получить существующую ячейку и, вероятно, должны использовать _2_ в классе _3_.


person Mohammed Asheeba    schedule 13.05.2017    source источник
comment
Используйте отладчик и пройдитесь по коду. Кстати, нет причин делать _1_ необязательным. Если на самом деле это не экземпляр _2_, вы хотите, чтобы он рухнул, так как это явная ошибка в вашем приложении. Затем вы можете избавиться от всех этих ненужных _3_ во всех _4_ ссылках. И тогда вы можете избавиться от этих неприятных операторов _5_ (что означает сбой здесь).   -  person Scott Thompson    schedule 13.05.2017
comment
@ScottThompson Я не получаю журнал сбоев, он просто вылетает и показывает мой класс AppDelegate (Thread1: EXC_BAD_ACCESS~)   -  person rmaddy    schedule 13.05.2017
comment
@rmaddy удалил метки, которые все еще вылетают, если я возвращаю CGSize (ширина: 375, высота: 600) без каких-либо вещей, все работает нормально. но как только ячейка задействована, происходит сбой, и причина не отображается   -  person Mohammed Asheeba    schedule 13.05.2017
comment
У меня похожая проблема, но только когда я использую атрибутированный текст в своей ячейке. Вы должны использовать let sizingView = Bundle.main.loadNibNamed(MyNib, owner: self, options: nil)?[0] as? MyCell   -  person Mohammed Asheeba    schedule 13.05.2017
comment
пусть sizingView = Bundle.main.loadNibNamed(MyNib, владелец: я, параметры: ноль)?[0] как? MyCell, но это не решает проблему   -  person Ryan Heitner    schedule 31.07.2017


Ответы (1)


Можете выложить крашлог или хотя бы верхнюю часть крашлога?

person Scott Thompson    schedule 13.05.2017
comment
Причина: '- [NSCFSTRING SETSIZEHASBESBESTESET:]: Недознанный селектор, отправленный на экземпляр 0x610000076BC0' *** Стек первого броска: (0 Corefoundation 0x0000000109dd9d4b __exceptionpreprocess + 171 1 libobjc.a.dylib 0x00000001094d921e objc_Exception_throw + 48 2 Corefoundation 0x0000000109E49F04 - [ NSObject (NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x0000000109d5f005 ___ пересылка _ + 1013 4 CoreFoundation 0x0000000109d5eb88 _CF_forwarding_prep_0 + 120 5 UIKit 0x00000001080d9485 - [UICollectionViewFlowLayout _getSizingInfosWithExistingSizingDictionary:] + 3691 6 UIKit 0x00000001080da97b - [UICollectionViewFlowLayout _fetchItemsInfoForRect:] + 127 7 UIKit 0x00000001080d3504 -[UICollectionViewFlowLayout prepareLayout] + 273 8 UIKit 0x00000001080f3d6c - [UICollectionViewData _prepareToLoadData] + 159 9 UIKit 0x00000001080f4618 - [UICollectionViewData validateLayoutInRect:] + 57 10 UIKit 0x000000010809b6d4 - [UICollectionView layoutSubviews] + 232 11 UIKit 0x0000000107817ab8 - [UIView (CALayerDelegate) layoutSublayersOfLayer:] + 1 237 12 QuartzCore 0x0000000106fcdbf8 - [ CALayer layoutSublayers] + 146 13 QuartzCore 0x0000000106fc1440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366 14 QuartzCore 0x0000000106fc12be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24 15 QuartzCore 0x0000000106f4f318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280 16 QuartzCore 0x0000000106f7c3ff _ZN2CA11Transaction 6commitEv + 475 17 QuartzCore 0x0000000106f7cd6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113 18 CoreFoundation 0x0000000109d7e267 <сильный> CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 19 CoreFoundation 0x0000000109d7e1d7 __CFRunLoopDoObservers + 391 20 CoreFoundation 0x0000000109d628a6 CFRunLoopRunSpecific + 454 21 UIKit 0x000000010774caea - [UIApplication _run] + 434 22 UIKit 0x0000000107752c68 UIApplicationMain + 159 23 Moden 0x0000000104ab4fbf main + 111 24 libdyld.dylib 0x000000010ad4e68d start + 1 ) libc++abi.dylib: завершение с необработанным исключением типа NSException (lldb) - person Ryan Heitner; 31.07.2017