【发布时间】:2018-07-27 04:04:38
【问题描述】:
现在,我遇到了一个问题。
我设法将单元格的内容视图包装到它的标签上,但是有些间距不适合设计。单元格之间有一些可用空间
这是我的代码
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 4
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let hastag = Hastag.fetchHastag()[indexPath.row]
let approximateWidth = view.frame.width - 20
let size = CGSize(width: approximateWidth, height: 28)
let attribute = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]
let estimatedFrame = NSString(string: hastag.hastag).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attribute, context: nil)
return CGSize(width: estimatedFrame.width + 20, height: 26)
}
下面是结果
这就是我想要实现的,它会是这样的
更新
这是我收集视图数据源和委托的完整代码。 Hastag.hastag 是字符串类型
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Hastag.fetchHastag().count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hastagCell", for: indexPath) as! HastagCollectionViewCell
cell.hastag = Hastag.fetchHastag()[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 4
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let hastag = Hastag.fetchHastag()[indexPath.row]
let approximateWidth = view.frame.width - 20
let size = CGSize(width: approximateWidth, height: 28)
let attribute = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)]
let estimatedFrame = NSString(string: hastag.hastag).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attribute, context: nil)
return CGSize(width: estimatedFrame.width + 16, height: 26)
}
【问题讨论】:
-
使用自定义布局'UICollectionViewLeftAlignedLayout'就可以了
-
你的意思是我必须使用图书馆? @Anuraj
-
是的..我用过这个
-
有什么想法可以让我在不使用库的情况下实现它吗? @Anuraj
-
@Anuraj 谢谢老兄,我终于使用了你推荐的(TagListView)库
标签: ios swift uicollectionview uicollectionviewcell