2017-08-14 81 views
0

我已經觀看了很多針對UICollectionView和UITableView的YT教程,即使這個應用程序,我正在尋找幫助是通過觀看和閱讀幾個教程,但有一個問題,我找不到。swift CollectionView單元格textLabel自動調整大小

這個應用程序是由用戶決定其用戶名,並用該用戶名寫一些文本。我已經使用Firebase進行了這項工作,連接了所有內容,即使是發佈回到應用程序,但問題是始終只顯示兩行文本。

這是怎麼樣子,所以你可以想像更好:

enter image description here

我想這爲textLabel以上用戶名朝向下展開與裏面寫全文。 該文本標籤上的行數設置爲0.我在故事板中嘗試了幾件事情,其中​​有許多不同的代碼和方法,但結果始終相同。 我應該在TableView中做這個嗎?我認爲collectionView是更好的方法,更容易設計明智。

下面是此頁VC代碼:

import UIKit 
import Firebase 

class FeedViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { 

    @IBOutlet weak var collectionView: UICollectionView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     loadData() 
    } 

    var fetchPosts = [Post]() 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    func loadData() { 
     self.fetchPosts.removeAll() 
     let ref = Database.database().reference() 
     ref.child("Frusters").observeSingleEvent(of: .value, with: { (snapshot) in 
      if let postDict = snapshot.value as? [String:AnyObject] { 
       for (_,postElement) in postDict { 
        print(postElement); 
        let post = Post() 
        post.username = postElement["Username"] as? String 
        post.message = postElement["Message"] as? String 
        self.fetchPosts.append(post) 
       } 
      } 
      self.collectionView.reloadData() 

     }) { (error) in 
      print(error.localizedDescription) 
     } 
     ref.removeAllObservers() 
    } 

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

     let deviceSize = UIScreen.main.bounds.size 
     //let cellSize = sqrt(Double(deviceSize.width * deviceSize.height)/(Double(33))) 

     let cellWidth = ((deviceSize.width/2) - 10) 
     let cellHeight = (deviceSize.height/4) 

     return CGSize(width: cellWidth , height: cellHeight) 
    }*/ 

    func numberOfSections(in collectionView: UICollectionView) -> Int { 
     return 1 
    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return self.fetchPosts.count 
    } 

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

     cell.messageLabel.text = self.fetchPosts[indexPath.row].message 
     cell.usernameLabel.text = self.fetchPosts[indexPath.row].username 

     return cell 
    } 

    /*func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeFotItemAt indexPath: IndexPath) -> CGSize { 
     return CGSize (width: view.frame.width, height: 500) 
    }*/ 
} 

你可以看到一些我已經測試它的代碼現在是在「評論」的方式,因爲他們什麼也沒做不同的。

你能告訴我我做錯了什麼嗎?是故事板中的東西,還是我插入錯誤的代碼,可能根本沒有插入任何所需的代碼?

+0

你有沒有向故事板中的UILabel添加任何高度約束? – Amit

+0

不,我沒有。我實際上刪除了單元格內的所有約束,所以我可以看到是否有可能設置了錯誤。 –

+1

[如何使UICollectionview單元格高度動態?](https:// stackoverflow。com/questions/38759138/how-to-make-uicollectionview-cell-height-dynamic) –

回答

0

您可以更新標籤的preferredWidth,或者只需添加大於或等於值的高度限制。

P.S.確保你有numberOfLines屬性設置爲所以標籤沒有最大數量的行將截斷字符串以及。

+0

我的行數設置爲0(不在代碼中,但在故事板中)。你能告訴我在哪裏更新preferredWidth?在collectionView func? –

+0

@PejoZmaj在'cellForItemAtIndexPath'方法中調用它,然後執行'yourLabel.setNeedsLayout()',然後執行'yourLabel.layoutIfNeeded()'以應用更改 – Pancho

0

根據估計字符串將採用的高度,您可以爲每個單元格分配一個動態高度。那麼,如果你的標籤的numberOfLines設置爲0(無限)或者讓我們說4〜5,那麼它會按你的意願工作。

注意:您的標籤在每個單元格內的高度限制也應該設置爲可以擴展到多個要顯示的行數。

估算串的高度:

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

     return ceil(boundingBox.height) 
    } 
} 

UICollectionView佈局委託

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeFotItemAt indexPath: IndexPath) -> CGSize { 
    let messageHeight = self.fetchPosts[indexPath.row].message.height(yourConstrainedWidth, yourFont) 
    let height = height of other stuff including margins + messageHeight 
    return CGSize (width: view.frame.width, height: height) 
} 
+0

謝謝您的回答和支持。我會嘗試使用UITableView。 :) 我發現了很多UITV的教程,但我試圖用它以某種方式將它轉換爲UICV。那麼,那不好,讓我們現在嘗試與UITV:D - 再次感謝您的幫助;) –

0

謝謝大家。你是對的。我已經在TableView中創建了它,使用相同的結果更容易。我已經做到了,所以我正在轉向這個應用程序的下一個級別。

謝謝大家的幫助;)