How to use Storyboard to lay out screen content th

2019-03-03 11:14发布

问题:

This question already has an answer here:

  • How to add objects to a UIScrollView that extend beyond UIView from Storyboard? 3 answers

I use swift 2.0 for programming and I'm confused with adding more objects on view controller. For example, I need 14 buttons on my view controller with required constraints. But I'm able to add only 7 buttons one by one in my view controller on story board. Because no more place to add objects on view controller. So, How to add number of objects in view controller on story board?. Please refer following screen shots. Thanks for your help friends.

View controller on story board:

I'm able to add only 7 buttons with proper constraints. but i need to add 14 buttons with proper constraints. when view controller is scrolled then the button 8 to 14 will shown one by one respectively button 1 to 7.

Output on iPhone 5 without scroll view :

Output on iPhone 4s with scroll view:

I need like this on iPhone 5 , but 14 buttons. The 8 to 14 buttons arranged respectively 1 to 7 buttons.

回答1:

You can lay this out in a Storyboard.

  1. Click on your viewController, and then in the Size Inspector, set the Simulated Size to Freeform and set the width to 320 and the height to 1136. This will give you a tall skinny layout.

  2. Add a scrollView to that. Size the scrollView to the full screen. Pin all four of its sides to its superView.

  3. Add a UIView to the scrollView. This is your contentView. Size the content view to the full screen. Pin all four of its sides to the scrollView.
  4. Set an Equal Widths constraint between the contentView and the scrollView. This will only allow it to scroll vertically.
  5. Set a height constraint of 1136 for the contentView.
  6. Lay out your 14 buttons in the tall viewController.

When you run, your contentView will scroll.




回答2:

You can add button so easily by using some codes instead of Storyboard.

    let scrView = UIScrollView(frame: CGRect(x: 0, y: 0, width: SCR_W, height: SCR_H))
    for idx in 1...14 {
        let button = UIButton(frame: CGRectMake(0, 0, btnWidth, btnHeight))
        button.center = CGPointMake(SCR_W/2, offset * idx)
        button.setTitle("Button\(idx)", forState: .Normal)
        button.tag = idx
        button.addTarget(self, action: #selector(self.onClick(_:)), forControlEvents: .TouchUpInside)
        scrView.addSubview(button)
    }

    scrView.contentSize = CGSizeMake(SCR_W, offset * 14)
    self.view.addSubView(scrView)

    -------->

    func onClick(let btn:UIButton) -> Void {
    switch btn.tag {
       case 1:
       case 2:
       case 3: 
     ...  ... ...
       default:

    }
}


回答3:

You can change your viewController size in Storyboard.

select viewController and change size to Freedom (fig1.)

   fig1.

select view of viewController and change frame. (fig2.)

   fig2.