0
votes

I have a problem with my UIScollView who scrolls vertically. I just want my ScollView scroll horizontally. I've tried to change the contentSize but that doesn't worked.

I use constraints, and this code :

var plugeeNews : [Plugs]?

var topNewsScrollView : UIScrollView = {
        var scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 75))
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.backgroundColor = .gray
        scrollView.isDirectionalLockEnabled = true
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        return scrollView
    }()


func setupViewInTopNewsScrollView() {
        for i in 0..<plugeeNews.count {
            let xPosition = screenSize.width * CGFloat(i)
            let myView = TopNewsCell(frame: CGRect(x: xPosition, y: 0, width: screenSize.width , height: heightOfNewsCell))
            myView.label.text = plugeeNews[i]
            myView.randomBackgroundColor(number: i)
            topNewsScrollView.contentSize = CGSize(width: topNewsScrollView.frame.width * CGFloat(i + 1),height:  heightOfNewsCell)
            topNewsScrollView.addSubview(myView)
        }
    }

This is the height constraint of my UIScrollView :

...
        topNewsScrollView.heightAnchor.constraint(equalToConstant: heightOfNewsCell).isActive = true

And this is the result :

enter image description here

And I don't want the gray view below the white/gray views on the UIScollView, i just want to swipe between my views horizontally.

1
Why are you setting the contentSize of your UIScrollView each time you add a new UIView ?? - Victor Sigler
You should read carefully this tutorial raywenderlich.com/122139/uiscrollview-tutorial - Victor Sigler
Victor : it's to avoid to create a new variable to save the i value. Ah ok I'm going to read the tutorial, thanks - Mathis Delaunay
The contentSize should be assigned only once not every time as you're doing in the above code - Victor Sigler

1 Answers

-1
votes

Set the content size:

scrollContainer.contentSize = CGSize(width:10000, height:50)