Search code examples
iosswiftxcodetableviewcollectionview

I want create this Sliding UIVies in xcode using swift, what sholud i used ? an collecntionView or TableView?


i want to create an exact screen in my ios application with xcode & swift im not able to create it, what shall i used? an collectionView or ScroolView?

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{


@IBOutlet weak var newCollectionView: UICollectionView!






override func viewDidLoad() {
    super.viewDidLoad()
    newCollectionView.delegate = self
    newCollectionView.dataSource = self
    // Do any additional setup after loading the view, typically from a nib.
}


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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

}

enter image description here


Solution

  • It is my class. It works completely. Also i added an image of storyboard. Link to my github project : https://github.com/Agisight/scroller.git

    class ViewController: UIViewController, UIScrollViewDelegate {
        @IBOutlet weak var scroll: UIScrollView!
    
        @IBOutlet var btns: [UIView]!
        override func viewDidLoad() {
            super.viewDidLoad()
            scroll.delegate = self
        }
        func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
            methodAnimation()
        }
    
        func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
            methodAnimation()
        }
    
        func methodAnimation() {
            if btns.count == 0 {return}
    
            var i = 0
            // i – calculate it, it is your visible/desirable view.
            // here is variant of code
            let dragOffset = view.frame.width * 0.5 // callibrate it for you
            let offX = scroll.contentOffset.x
            i = Int(offX + dragOffset) / Int(view.frame.width)
    
            i = max(0, min(i, btns.count - 1))
            let yourX = btns[i].frame.width * CGFloat(i) // ()
            let p = CGPoint(x: yourX, y: 0);
            scroll.setContentOffset(p, animated: true)
        }
    }
    

    My UIViewController with scroll