Programmatically align a label from bottom of screen regardless of device - iOS

喜你入骨 提交于 2020-01-15 05:44:09

问题


I've tried

self.lblTimer = [[UILabel alloc] initWithFrame:CGRectMake(x,y,width,height)]; 

..but since the label i'm looking to position is at the bottom of the screen it goes out of view when i switch devices. I'm trying to make the label 10 pixels in from the left and 10 pixels up from the bottom. It should look consistent regardless if it's viewed on iPhone 4, 5, 6 or 6 plus.


回答1:


So, your question is about X and Y, right? The points in iOS start at the top left corner of the screen, so the top left corner of the screen is (0,0).

If you move up/down along the left edge, the X coordinate will continue to be 0. So if you want 10 points to the right of the left edge, X will be 10.

The bottom of the screen can be calculated this way:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

In here, the variable screenHeight will be the bottom line of the screen. So if you want 10 points above the line, you'll need to get (screenHeight - 10).

However, as mentioned by Lyndsey Scott in the comments below, this places the top left corner of your label in the top screenHeight - 10, which could (very likely with a value of 10) place your label out of sight. To solve this, you also subtract the height of the label so the label is in sight, in the correct spot.

So your final answer is:

CGRectMake(10,(screenHeight - height - 10),width,height);


来源:https://stackoverflow.com/questions/27234518/programmatically-align-a-label-from-bottom-of-screen-regardless-of-device-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!