Home > Blockchain >  How to combine UISlider and CollectionView to autoresizing the cells of the UICollectionViewCell
How to combine UISlider and CollectionView to autoresizing the cells of the UICollectionViewCell

Time:09-23

I need to create the next UI

User Interface

But i don't know where to start and how does the UISlider update the CollectionView's cells.

The idea is to use a ramdom JSON and render each item into the CollectionView's cells.

CodePudding user response:

// Set default value of how many cells to be displayed per row.
var numberOfItemsPerRow:Int = 4

override func viewDidLoad() {
    super.viewDidLoad()
    configureSlider()
}
func configureSlider() {
    let slider = UISlider(frame:CGRect(x: 0, y: 0, width: 300, height: 20))
    slider.center = self.view.center
    // minimum number of rows required
    slider.maximumValue = 1
    // maximum number of rows required
    slider.maximumValue = 10
    slider.value = 1
    slider.isContinuous = true
    stepper.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
    self.view.addSubview(stepper)
    numberOfItemsPerRow = Int(stepper.value)
}

@objc func sliderValueChanged(_ sender:UISlider!) {
    numberOfItemsPerRow  = Int(sender.value)
    
    self.collectionView.performBatchUpdates {
        self.collectionView.reloadData()
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (self.view.frame.width)/CGFloat(numberOfItemsPerRow)
    return CGSize(width: width, height: width)
}

Hope you can configure remaining delegate methods.

  • Related