iOS Simulator button not centered

2019-02-19 22:21发布

I'm following a tutorial to make a very simple game, yet I've run into a problem I can't figure out. When I center my button on the editor screen it all looks fine, but then running the app in the simulator seems to screw it all up:

problem

I'm running the latest version of XCode.

标签: ios xcode5
2条回答
2楼-- · 2019-02-19 23:15

I was having a lot of trouble with this, too. In Xcode 6 (and Xcode 7) here is what you do.

Use a Storyboard, not XIB files. This should be the default in Xcode 6 (and Xcode 7).

Use Auto Layout and Size Classes. This should also be the default. If you click Main.storyboard in the Project Navigator and then show the File inspector you can make sure that these are checked:

enter image description here

Select your button on the storyboard. Then click the align button on the bottom right. Select "Horizontal Center in Container" and "Vertical Center in Container". Click "Add 2 Constraints".

enter image description here

If it wasn't perfectly centered already you may need to do one more thing. Click the "Resolve Auto Layout Issues" button that is two to the right of the align button. Choose "Update Frames" under "Selected Views".

enter image description here

Now when you run your app it should be centered no matter what device size you are using.

I learned all this from Creating the user interface – Auto layout. I recommend you check it out.

查看更多
放荡不羁爱自由
3楼-- · 2019-02-19 23:17

You need to use autolayout to set some constraints on the button. If you don't use autolayout, the layout just uses the raw X and Y values. So in landscape, the heights of the screen are the same, but the widths are different. Your button lays out at the same X value on both screens, so one will be centered and one won't be.

Check out this tutorial for more info on layout constraints.

查看更多
登录 后发表回答