具有多行的UICollectionView

时间:2017-02-07 10:41:41

标签: ios swift uicollectionview

我使用UICollectionView(使用UIButtons的视图)预订时间:

    override func viewDidLoad() {
        super.viewDidLoad()        
        collectionViewTime.register(UINib(nibName: "TimeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "timecell")
        collectionViewTime.dataSource = self
        collectionViewTime.delegate = self        
        if let layout = collectionViewTime.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .vertical
        }

    }

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

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {            
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let numberOfItems = CGFloat(collectionView.numberOfItems(inSection: 0))
        let combinedItemWidth = (numberOfItems * flowLayout.itemSize.width) + ((numberOfItems - 1)  * flowLayout.minimumInteritemSpacing)
        let padding = (collectionView.frame.width - combinedItemWidth) / 2
        return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {            
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timecell", for: indexPath) as! TimeCollectionViewCell            
        let time = Timeline[indexPath.row][0]
        cell.btnTime.setTitle(DateManager.dateToTime(date: time.0), for: .normal)            
        return cell
    }

我在一行中得到了所有观点(UIButtons): UICollectionView 如何在新行中设置自动移动的UIView? 因此,在我的情况下(iPad),一行将包含7个UIViews,iPhone将在一行中包含4-5个UIViews。

2 个答案:

答案 0 :(得分:1)

为此,您需要实施UICollectionViewDelegateFlowLayout方法collectionView(_:layout:sizeForItemAt:)并将collectionView的{​​{1}}更改为Scroll direction

Vertical

答案 1 :(得分:0)

请再使用一个流代理方法,如下所示

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize;
------
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width:(button width), height:button hieght);
    }