0

I current have a collectionview attached to a array of strings. I want to align these cells center regardless of the number of things in the array. I am not sure how to do it, and where to do it.

import UIKit
class MyButtonCell: UICollectionViewCell{
    @IBOutlet weak var buttonOne: UIButton!
    @IBOutlet weak var targetButton: UIButton!
    
    var callback: (() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
        
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        contentView.layer.borderWidth = 1
        contentView.layer.borderColor = UIColor.black.cgColor
    }
    
    @IBAction func buttonTapped(_ sender: UIButton) {
        
        callback?()
    }
}

class StevenViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    let buttonTitles: [String] = [
        "4", "6", "7", "8"
    ]
    
    var targetButtonTitles: [String] = [
        "", "", "", ""
    ]
    
    var current:String = ""
    
    @IBOutlet var collectionView: UICollectionView!
    
    @IBOutlet var targetCollection: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        targetCollection.delegate = self
        targetCollection.dataSource = self
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.tag = 1
        targetCollection.tag = 2
        
 
        
    }
    func centerItemsInCollectionView(cellWidth: Double, numberOfItems: Double, spaceBetweenCell: Double, collectionView: UICollectionView) -> UIEdgeInsets {
        let totalWidth = cellWidth * numberOfItems
        let totalSpacingWidth = spaceBetweenCell * (numberOfItems - 1)
        let leftInset = (collectionView.frame.width - CGFloat(totalWidth + totalSpacingWidth)) / 2
        let rightInset = leftInset
        return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         if collectionView.tag == 1 {
               return buttonTitles.count
            } else {
               return targetButtonTitles.count
           }
        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      


           // set the button title (and any other properties)

               
           if collectionView.tag == 1 {
              
               // Setup here your cell
   
         
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
         
               cell.callback = {
             
                   print("Button was tapped at \(indexPath)")
                   self.targetButtonTitles[indexPath.item] = self.buttonTitles[indexPath.item]
                   
                   //print(self.targetButtonTitles)
                    self.current = self.buttonTitles[indexPath.item]
                
                    print(self.current)
               //collectionView.reloadData()
              
                   
             
                   // do what you want when the button is tapped
               }

               cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])

               return cell
           } else {

               // Setup here your targetCell
             let targetCell = targetCollection.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
     
            targetCell.callback = {
                
                
                if self.current != ""{
                     
                    
                    self.targetButtonTitles[indexPath.item] = self.current
                    
                    print(self.targetButtonTitles)
                    
                      targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
                 
                    self.current = ""
                 

                }else{
                    self.targetButtonTitles[indexPath.item] = ""
                    targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
                    
                    
                }
                 

            }
            
                return targetCell
               
           }
        
    }
}

As you can see, right now they are just starting from the left. So, How should I align them in the middle.

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Steven Oh
  • 382
  • 3
  • 14
  • 1
    Checkout this solution: https://stackoverflow.com/a/37065909/3278326 – Jarvis The Avenger Jun 29 '20 at 04:03
  • Does this answer your question? [How to center horizontally UICollectionView Cells?](https://stackoverflow.com/questions/34267662/how-to-center-horizontally-uicollectionview-cells) – Amit Jun 29 '20 at 04:36
  • @Amit hey, thanks for the recommendation. I used those functions, but they don't seem to center - the whole view just shifted a few units to the right. – Steven Oh Jun 29 '20 at 04:54
  • Have you added the protocol UICollectionViewDelegateFlowLayout? – Kai Zheng Jun 29 '20 at 05:40

0 Answers0