ios - 水平 Collection View 内容宽度和间距

标签 ios swift uicollectionview uicollectionviewcell

enter image description here

如何使我的水平 Collection View 标签宽度包裹标签的内容宽度并使它们之间的间距相等?目前我的 Collection View 单元格宽度为 100。如果我增加宽度以适应其他标签,较短的标签之间的间距会更大。任何想法将不胜感激。

最佳答案

先用与文本关联的字体计算标签文本的宽度。

extension String {
    func size(with font: UIFont) -> CGSize {
        let fontAttribute = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttribute)
        return size
    }
}

collectionView(_, collectionViewLayout:_, sizeForItemAt) 中返回计算出的宽度和 collectionView 的高度。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let newWidth = titles[indexPath.row].size(with: labelFont!).width + 10 //Added 10 to make the label visibility very clear
    return CGSize(width: newWidth, height: collectionView.bounds.height)
}

完整源代码:

class ViewController: UIViewController {

    @IBOutlet weak var collection: UICollectionView!

    let labelFont = UIFont(name: "Helvetica Neue", size: 18)
    let titles = ["Hi", "Hello", "HorizontalCollectionView", "VerticalCollectionView"]

    override func viewDidLoad() {

        super.viewDidLoad()
        collection.backgroundColor = UIColor(red: 68/255, green: 143/255, blue: 1, alpha: 1)
        collection.register(UINib.init(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")
    }
}

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

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

        return titles.count
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

        return 10 // Adjust the inter item space based on the requirement.
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let newWidth = titles[indexPath.row].size(with: labelFont!).width + 10 //Added 10 to make the label visibility very clear
    return CGSize(width: newWidth, height: collectionView.bounds.height)
}

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCollectionViewCell", for: indexPath) as! CustomCollectionViewCell
        cell.titleLabel.text = titles[indexPath.row]
        cell.titleLabel.font = labelFont!
        return cell
    }
}

extension String {
    func size(with font: UIFont) -> CGSize {
        let fontAttribute = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttribute)
        return size
    }
}

另一个解决方案:

ViewController.swift

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    @IBOutlet weak var collView: UICollectionView!


    var tasksArray = ["To Do", "SHOPPING","WORK"]
    var selectedIndex = Int()

    override func viewDidLoad() {
        super.viewDidLoad()
        collView.register(UINib.init(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
        let layout = collView?.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = UICollectionViewFlowLayout.automaticSize
        layout.estimatedItemSize = CGSize(width: 170, height: 50)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tasksArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
        cell.lblName.text = tasksArray[indexPath.row]
        if selectedIndex == indexPath.row
        {
            cell.backgroundColor = UIColor.lightGray
        }
        else
        {
            cell.backgroundColor = UIColor.white
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
        self.collView.reloadData()
    }
}

Cell.swift

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var lblName: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        layer.borderWidth = 1
        layer.cornerRadius = bounds.height / 2
    }

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var frame = layoutAttributes.frame
        frame.size.width = ceil(size.width)
        layoutAttributes.frame = frame
        return layoutAttributes
    }
}

关于ios - 水平 Collection View 内容宽度和间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193629/

相关文章:

iOS 从动态 TableViewCell 中保存文本

ios - 在 Angular 6 微应用中选取图像后,ImagePicker 关闭到黑屏

ios - 快速读取 pList

ios - 如何在每个 View 中显示文本的页面控件

swift - 为什么我的 Collection View Cells 不显示在 iPhone 模拟器中?

ios - UICollectionView 不允许完全滚动---最后几行被切断

ios - C# - Xamarin - HttpClient - 由于对象的当前状态,操作无效 - iOS

ios - 如何根据 Childviewcontroller(UIViewController 的不同大小)高度更改容器 View (父 View )的高度?

json - “表达类型是模棱两可的,没有更多上下文”, swift 3

ios - UITableView with UICollectionView in row weird scroll in different rows at the same time