1
votes

I have a UIView that is placed inside of a scrollView. The UIView has 4 constraints that I have set in storyboard:

  • Equal Width To scrollView (w/ a 0.98 multiplier)
  • Equal Height To scrollView (w/ a 0.98 multiplier)
  • Horizontally Centered inside scrollView (w/ constant = 0)
  • Vertically Centered inside scrollView (w/ constant = 0)

The scrollView has the regularly trailing, leading, top, & bottom constraints with all constants = 0.

I have also set the following property for my scrollView.

self.scrollView.contentSize.width = self.scrollView.frame.size.width + 30

How could I center the UIView inside of my scrollView?

Note: I do have access to a self.horizontalCenterConstraint.constant, which can control where the UIView is located inside the scrollView. I tried doing

self.horizontalCenterConstraint.constant = (self.scrollView.contentSize.width / 2)

but this does not actually center the UIView inside the scrollView.

1
in which method do you set the contentSize and horizontalCenterConstraint? (viewDidLoad, viewWillAppera...)tbilopavlovic
This all occurs inside of a UITableViewCell, so I made the cell override traitCollectionDidChange(..), and that is where I set them. Also in awakeFromNib(..) initially.AppreciateIt
I think you need to add trailing, leading, top and bottom between view and scrollView, so scrollview can calculate how far view is from contentSize marginstbilopavlovic
Why do you use autolayout constraints and set scrollView.contentSize at the same time? You should either rely on autolayout OR manually set contentSize. developer.apple.com/library/ios/technotes/tn2154/_index.htmlFyodor Volchyok
and if you want your content to be 30 point wider than scrollView you could set it in constraint property named constant. In your case it's value is 30. When you solve issues with constraints autolayout should do the rest for you, no code needed.Fyodor Volchyok

1 Answers

1
votes

I suggest to add containerView as the root subview of scrollView (leading, trailing, top, bottom = 0 and equal width and height as scrollView) and then add this view that you want.

  • scrollView
    • containerView
      • YOUR_VIEW (same constraints as you already have)

Now scrollView can calculate the contentSize because of constraints of containerView, and i see that you added self.scrollView.contentSize.width = self.scrollView.frame.size.width + 30 so just set width of containerView wider than scrollView and it will scroll horizontally....