gpt4 book ai didi

layout - CollectionView 动态单元格高度 swift

转载 作者:IT王子 更新时间:2023-10-29 05:04:58 27 4
gpt4 key购买 nike

我正在尝试创建一个 Collection View ,其中的单元格显示可变长度的字符串。

我正在使用这个函数来设置单元格布局:

 func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize
{
var cellSize:CGSize = CGSizeMake(self.whyCollectionView.frame.width, 86)
return cellSize
}

我想做的是根据我的 cell.labelString.utf16Count 长度操纵 cellSize.height。基本逻辑是 sa that

if((cell.labelString.text) > 70){
cellSize.height = x
}
else{
cellSize.height = y
}

但是,我无法设法检索始终返回 nil 的单元格标签字符串长度。 (我认为它还没有加载...

为了更好的理解,这里是完整的代码:

// WhyCell section
var whyData:NSMutableArray! = NSMutableArray()
var textLength:Int!
@IBOutlet weak var whyCollectionView: UICollectionView!

//Loading data
@IBAction func loadData() {
whyData.removeAllObjects()

var findWhyData:PFQuery = PFQuery(className: "PlacesWhy")
findWhyData.whereKey("placeName", equalTo: placeName)

findWhyData.findObjectsInBackgroundWithBlock({
(objects:[AnyObject]!,error:NSError!)->Void in

if (error == nil) {
for object in objects {
self.whyData.addObject(object)
}

let array:NSArray = self.whyData.reverseObjectEnumerator().allObjects
self.whyData = array.mutableCopy() as NSMutableArray

self.whyCollectionView.reloadData()
println("loadData completed. datacount is \(self.whyData.count)")
}
})
}

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
self.loadData()


}

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

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

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:whyCollectionViewCell = whyCollectionView.dequeueReusableCellWithReuseIdentifier("whyCell", forIndexPath: indexPath) as whyCollectionViewCell

// Loading content from NSMutableArray to cell
let therew:PFObject = self.whyData.objectAtIndex(indexPath.row) as PFObject
cell.userWhy.text = therew.objectForKey("why") as String!
textLength = (therew.objectForKey("why") as String!).utf16Count
self.whyCollectionView.layoutSubviews()

// Displaying user information
var whatUser:PFQuery = PFUser.query()
whatUser.whereKey("objectId", equalTo: therew.objectForKey("reasonGivenBy").objectId)

whatUser.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]!, error: NSError!)->Void in

if !(error != nil) {
if let user:PFUser = (objects as NSArray).lastObject as? PFUser {
cell.userName.text = user.username
// TODO Display avatar
}

}
})

return cell
}

func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize
{
var cellSize:CGSize = CGSizeMake(self.whyCollectionView.frame.width, 86)
return cellSize
}

最佳答案

虽然上面的答案可能会解决您的问题,但它建立了一种分配每个单元格高度的相当粗略的方法。您被迫根据某些估计对每个单元格高度进行硬编码。处理此问题的更好方法是在 collectionview 的 sizeForItemAtIndexPath 委托(delegate)方法中设置每个单元格的高度。

我将在下面引导您完成有关如何执行此操作的步骤。

第 1 步:让您的类扩展 UICollectionViewDelegateFlowLayout

第 2 步:创建一个函数来估计文本的大小:此方法将返回适合您的字符串的高度值!

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

let size = CGSize(width: yourDesiredWidth, height: height)
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(18, weight: UIFontWeightLight)]

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

第 3 步:使用或覆盖下面的委托(delegate)方法:

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

//we are just measuring height so we add a padding constant to give the label some room to breathe!
var padding: CGFloat = <someArbitraryPaddingValue>

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

关于layout - CollectionView 动态单元格高度 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27285258/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com