简体   繁体   中英

How to adjust view size for iPad and iPhone 4S without storyboard?

I don't know how to adjust view size for iPad and iPhone 4S without storyboard.

Is Auto layout used only in storyboard? Can't I set it by code?

And for example, if I make the game that has different things depends on the stage, using storyboard is not the right way I think...

Is there a good way to adjust view size for iPad and iPhone 4s without storyboard?

The answer to your question is: Yes.

It is fairly straightforward to use autolayout without IB. But there are a number of steps involved.

Here's a quick example of setting a subview to be the same size at the main view in a viewController (could be in viewDidLoad(), viewWillAppear(), etc.)

self.view.addSubview(viewToAutosize)
viewToAutosize.translatesAutoresizingMaskIntoConstraints = false
viewToAutosize.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
viewToAutosize.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
viewToAutosize.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
viewToAutosize.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

Some gotchas:

you need to set translatesAutoresizingMaskIntoConstraints to false on the view you wish to autosize.

you can't modify the constraints unless the view is already added as a subview (the view you are constraining against needs to be in the same view hierarchy -- see the first line of code above).

you have to activate the constraints manually. I have shown just one possible way to do it.

You should google auto "layout programmatically" (without the quotes) and pick a tutorial, video or apple documentation you are comfortable with to learn more. There's a lot you can do with auto layout, and it is definitely the future, since more device sizes are being added all the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM