2016-10-10 2 views
0

I dynamische Zellgröße in Textview per Text wollen, ist Hier mein CodeDynamische Höhe für UICollectionViewCell

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
     { 
      return DataArray.count 
     } 
     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
     { 
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CustomCollectionViewCell 

      let fixedWidth = cell?.TextView.frame.size.width 
      cell?.TextView.sizeThatFits(CGSize(width: fixedWidth!, height: CGFloat.greatestFiniteMagnitude)) 
      let newSize = cell?.TextView.sizeThatFits(CGSize(width: fixedWidth!, height: CGFloat.greatestFiniteMagnitude)) 
      var newFrame = cell?.TextView.frame 
      newFrame?.size = CGSize(width: max((newSize?.width)!, fixedWidth!), height: (newSize?.height)!) 
      cell?.TextView.frame = newFrame! 
      TextViewFrame = newFrame! 
      cell?.TextView.text = DataArray[indexPath.row] as? String 
      return cell! 
     } 
     func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
     { 

      return CGSize(width: CV.frame.size.width, height: 200) 
     } 

Hier i für Zelle 200 feste Größe gegeben haben. es gibt mir Ausgabe als unten Es gibt mir Zelle Höhe 200 für kleinen Inhalt sowie für großen Inhalt. Aber eigentlich möchte ich Zelle Höhe nach Inhalt. Wie kann ich das erreichen? Jede Hilfe wird geschätzt. Vielen Dank im Voraus enter image description here

+0

Gibt es eine maximale Grenze für die Länge der Zeichenfolge, die Sie in der Bezeichnung anzeigen werden? – Adeel

+0

Nein, ich habe keine maximale Grenze angewendet –

+0

Und was ist mit der minimalen Höhe einer Zelle? Besteht die Möglichkeit, dass die Zeichenfolge für eine Zelle leer ist? – Adeel

Antwort

0

Sie können die Höhe der Zelle finden, sobald Sie den Begrenzungsrect für den Text kennen, den Sie anzeigen möchten.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 

    let text = "String that you want to show in the label inside the cell" 
    let boundingRect = NSString(string: text).boundingRectWithSize(CGSizeMake(collectionView.bounds.width, 1000), 
                    options: .UsesLineFragmentOrigin, 
                    attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)], 
                    context: nil) 

    let size = CGSizeMake(collectionView.bounds.width, ceil(boundingRect.height)) 

    return size 
} 

Nur sicher sein, für die oben/unten/links/rechts Ränder Ihres label zum cell zu bilden.