Search code examples
iosswiftuiscrollviewautolayoutuikit

Vertical UIScrollView programmatically


I added some constraints but it scrolls horizontally, Where is the problem how can I manage it to scroll vertically? I tried to add some extra points to the width and height of contentSize separately but no results it keeps scrolling horizontally.

  1. And I just realized second problem my fav button inside UIView started not working after I added ScrollView, however, button added to the UIView that subview of ContentView which inside of ScrollView. Thanks in Advance!
private func setupScrollView() {
      self.view.addSubview(scrollView)
      scrollView.addSubview(contentView)
      scrollView.translatesAutoresizingMaskIntoConstraints = false
      contentView.translatesAutoresizingMaskIntoConstraints = false
      
      scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height + 1000)
      
      NSLayoutConstraint.activate([
          scrollView.topAnchor.constraint(equalTo: self.view.topAnchor),
          scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
          scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
          scrollView.leadingAnchor.constraint(equalTo:self.view.leadingAnchor)
      ])
          NSLayoutConstraint.activate([
              contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
              contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
              contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
              contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
      ])

Solution

  • You need to set the height of the content for the UIScrollView in the viewWillLayoutSubviews:

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.scrollView.contentSize.height = self.view.frame.height + 1000
    }
    

    And remove this line: scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height + 1000)