How can I use Autolayout to set constraints on my UIScrollview?

后端 未结 18 1655
别那么骄傲
别那么骄傲 2020-11-28 00:43

I have spent two days trying out the various solutions for Mixed and Pure Autolayout approaches to achieve what was a trivial scrollview setup prior to autolayout, and it\'s

18条回答
  •  迷失自我
    2020-11-28 01:40

    I spent days trying to find a solution of how to use AutoLayout view an embedded Scrollview, to centre the scrollview in the visible screen, that works across all devices / screen dimensions as well as with screen rotation.

    I spent days trying to do it with Autolayout only, and got close but never close enough. So in the end I had to add 3 lines of code per screen as well, in viewDidLoad.

    See solution below :

    1. Create the scrollview and fill it with whatever objects you want
    2. Turn on auto layout
    3. Then Centre the ScrollView Vertically and Horizontally Centre ScrollView
    4. Select the View and then 'Add missing constraints' - this then does its thing
    5. The result is that the a lot of constraints are generated. There are 2 new ones created for the view : 'Horiz space scrollview to View' and 'Vert space scrollview to view' or vice-versa.
    6. Delete the 'Horiz space scrollview to View' so you are now left with 3 constraints on the View. The 2 for entering the scrollview in the view and the one to set a vertical space between the scrollview and the view
    7. Now link the Vert constraint to your code by click and Ctrl dragging it to the header file and creating an NSLayoutConstraint IBOutlet (I called mine constraintVertVtoSV)
    8. Now go to the .m file and add these lines of code into viewDidLoad (play with the padding amount to get the correct vert centering)

      if (IPAD)
      

      { self.constraintVertVtoSV.constant = 150.0; }

    9. this should now run on all devices and be properly centered and still scroll properly.

提交回复
热议问题