0

В моем приложении Swift я использую UICollectionView. Каждый UICollectionViewCell содержит UILabel, и в какой-то момент я заполняю эти метки разными строками из моего массива. Тем не менее, строки имеют разную длину, поэтому я хотел бы отображать их с правильным размером. В настоящее время я использую эти два метода:
Почему я не могу изменить ширину моего UICollectionViewCell на основе длины ярлыка внутри?

private func estimateFrameForText(text: String) -> CGRect { 
     //we make the width arbitrarily large so we don't undershoot height in calculation 
     let width: CGFloat = 200 

     let size = CGSize(width: width, height: 33) 
     let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) 
     let attributes = [NSFontAttributeName: font] 

     return NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil) 
    } 

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
     var width: CGFloat = 200 

     //we are just measuring width so we add a padding constant to give the label some room to breathe! 
     var padding: CGFloat = 1 

     //estimate each cell's width 
     if let text = self.suggestedHashtags[indexPath.item] as? String { 
      width = estimateFrameForText(text: text).width + padding 
     } 
     return CGSize(width: width, height: 35) 
    } 

, но он не работает, клетки остаются теми же размерами. Что мне не хватает?

+0

ли вы показать свой вывод, что вы достичь и что вы на самом деле хотите. поэтому у нас появилась идея –

ответ

3

Я думаю, вы можете изменить ширину UICollectionViewCell.

В методе sizeForItemAtIndexPath вы можете установить размер UICollectionViewCell по следующему коду:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
{ 
    var size = CGSizeZero 
    if let text = self.suggestedHashtags[indexPath.item] as? String { 
     size = text.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18.0)]) 
     return size 
    } 
    return size 
} 
2

UICollectionViewDelegateFlowLayout Используйте метод делегатов.

class CONTROLLERNAME: UIViewController ,UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{ 

var items = ["12", "2", "3221", "434", "52342","5646445646454464654646464", "bdvjsd", "adscfaaaw", "How are you?"]; 


func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
     return CGSize(width: self.findHeightWidthForText(self.items[indexPath.item], havingWidth: self.view.frame.size.width - 18, andFont: UIFont.systemFontOfSize(17.0)).width + 12, height: 36) // here pass your font size and ya give extra some space for cell. 
} 


// method for find hight and width for particular string. 
func findHeightWidthForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize { 
     var size = CGSizeZero 
     if text.isEmpty == false { 
      let frame = text.boundingRectWithSize(CGSizeMake(widthValue, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) 
      size = CGSizeMake(frame.size.width, ceil(frame.size.height)) 
     } 
     return size 
    } 

Выход:

Output