我已經觀看了很多針對UICollectionView和UITableView的YT教程,即使這個應用程序,我正在尋找幫助是通過觀看和閱讀幾個教程,但有一個問題,我找不到。swift CollectionView單元格textLabel自動調整大小
這個應用程序是由用戶決定其用戶名,並用該用戶名寫一些文本。我已經使用Firebase進行了這項工作,連接了所有內容,即使是發佈回到應用程序,但問題是始終只顯示兩行文本。
這是怎麼樣子,所以你可以想像更好:
我想這爲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)
}*/
}
你可以看到一些我已經測試它的代碼現在是在「評論」的方式,因爲他們什麼也沒做不同的。
你能告訴我我做錯了什麼嗎?是故事板中的東西,還是我插入錯誤的代碼,可能根本沒有插入任何所需的代碼?
你有沒有向故事板中的UILabel添加任何高度約束? – Amit
不,我沒有。我實際上刪除了單元格內的所有約束,所以我可以看到是否有可能設置了錯誤。 –
[如何使UICollectionview單元格高度動態?](https:// stackoverflow。com/questions/38759138/how-to-make-uicollectionview-cell-height-dynamic) –