2016-10-03 83 views
5

-化妝UIcollectionView頭動態高度

我UIcollectionView與頭
的頭型是UICollectionReusableView
其有一個文本標籤,且該文本大小不固定的,它取決於什麼用戶輸入
所以我需要我HEADR拉伸依賴於標籤和其他物體的高度,我會添加到頭
這是我的故事板

enter image description here

這個

當我運行應用程序

enter image description here

+0

也許這是工作,但我不明白Objective-C,請我快速需要它 – joda

+0

http://stackoverflow.com/questions/37873537/how-to-dynamically-add-labels-and-buttons-in -section-header-of-uicollectionview – joda

+0

可能,問題是重複的:http:// stackoverflow。com/questions/25642493/dynamic-uicollectionview-header-size-based-uilabel –

回答

3

注輸出:這是斯威夫特3碼。

您的視圖控制器:

class ViewController: UIViewController { 
    @IBOutlet weak var collectionView: UICollectionView! 

    // the text that you want to add it to the headerView's label: 
    fileprivate let myText = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda." 
} 

extension ViewController: UICollectionViewDataSource { 
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 
     switch kind { 
     case UICollectionElementKindSectionHeader: 
      let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, 
                      withReuseIdentifier: "customHeader", 
                      for: indexPath) as! CustomCollectionReusableView 

      headerView.lblTitle.text = myText 
      headerView.backgroundColor = UIColor.lightGray 

      return headerView 
     default: 
      fatalError("this is NOT should happen!!") 
     } 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return 100 
    } 

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) 

     cell.backgroundColor = UIColor.brown 
     // ... 

     return cell 
    } 
} 

extension ViewController: UICollectionViewDelegateFlowLayout { 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 
     // ofSize should be the same size of the headerView's label size: 
     return CGSize(width: collectionView.frame.size.width, height: myText.heightWithConstrainedWidth(font: UIFont.systemFont(ofSize: 17))) 
    } 
} 


extension String { 
    func heightWithConstrainedWidth(font: UIFont) -> CGFloat { 
     let constraintRect = CGSize(width: UIScreen.main.bounds.width, height: CGFloat.greatestFiniteMagnitude) 
     let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) 

     return boundingBox.height 
    } 
} 

您的自定義UICollectionReusableView

class CustomCollectionReusableView: UICollectionReusableView { 
    @IBOutlet weak var lblTitle: UILabel! 

    override func awakeFromNib() { 
     super.awakeFromNib() 

     // setup "lblTitle": 
     lblTitle.numberOfLines = 0 
     lblTitle.lineBreakMode = .byWordWrapping 
     lblTitle.sizeToFit() 
    } 
} 

希望這有助於。

5

這驅使我要半天左右絕對是瘋了。 這是最後的工作。

確保在您的標題標籤被設定爲動態大小,一條線和包裝

  1. 在視圖中嵌入標籤。這將有助於自動調整。 enter image description here

  2. 確保您的標籤上的約束是有限的。例如:從底部標籤到可重用視圖的大於約束不起作用。見上面的圖片。

  3. 添加一個出口到你的子類,你在

    class CustomHeader: UICollectionReusableView { 
        @IBOutlet weak var contentView: UIView! 
    } 
    
  4. 嵌入您的標籤視圖無效的初始佈局

    override func viewWillLayoutSubviews() { 
        super.viewWillLayoutSubviews() 
    
        collectionView.collectionViewLayout.invalidateLayout() 
    } 
    
  5. 佈局的頭,以獲得正確的大小

    extension YourViewController: UICollectionViewDelegate { 
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 
    
         if let headerView = collectionView.visibleSupplementaryViews(ofKind: UICollectionElementKindSectionHeader).first as? CustomHeader { 
          // Layout to get the right dimensions 
          headerView.layoutIfNeeded() 
    
          // Automagically get the right height 
          let height = headerView.contentView.systemLayoutSizeFitting(UILayoutFittingExpandedSize).height 
    
          // return the correct size 
          return CGSize(width: collectionView.frame.width, height: height) 
         } 
    
         // You need this because this delegate method will run at least 
         // once before the header is available for sizing. 
         // Returning zero will stop the delegate from trying to get a supplementary view 
         return CGSize(width: 1, height: 1) 
        } 
    
    } 
    
+0

認識到這不一定適用於較長的列表,因爲返回到列表時標題將不可見。對於較短的列表,這仍然有效。 –