Я прочитал кучу сообщений о добавлении заголовка в UICollectionView. В приложении iOS 7+ в Swift я пытаюсь добавить заголовок с UILabel, в котором высота должна корректироваться в зависимости от высоты UILabel. UILabel имеет строки = 0.
Я установил заголовок в IB с помощью AutoLayout
ViewController реализует UICollectionViewDelegate, UICollectionViewDataSource
. Я не создал пользовательский класс для заголовка, но я использую эти две функции:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//description is a String variable defined in the class
let size:CGSize = (description as NSString).boundingRectWithSize(CGSizeMake(CGRectGetWidth(collectionView.bounds) - 20.0, 180.0), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 16.0)], context: nil).size
return CGSizeMake(CGRectGetWidth(collectionView.bounds), ceil(size.height))
}
func collectionView(collectionView: UICollectionView!, viewForSupplementaryElementOfKind kind: String!, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView! {
var reusableview:UICollectionReusableView = UICollectionReusableView()
if (kind == UICollectionElementKindSectionHeader) {
//listCollectionView is an @IBOutlet UICollectionView defined at class level, using collectionView crashes
reusableview = listCollectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "ListHeader", forIndexPath: indexPath) as UICollectionReusableView
let label = reusableview.viewWithTag(200) as UILabel //the UILabel within the header is tagged with 200
label.text = description //description is a String variable defined in the class
}
}
return reusableview
}
Отображение текста, похоже, работает, но расчет высоты не работает (см. снимок экрана ниже). Кроме того, я не думаю, что я могу получить доступ к UILabel через функцию collectionView...referenceSizeForHeaderInSection
. Любые предложения по правильному вычислению CGSize?