简体   繁体   English

以编程方式在不同屏幕尺寸下创建对象

[英]Programmatically create an object under different screen sizes

I am having the code below for creating an button. 我下面有用于创建按钮的代码。
Now the location of the button cannot be aligned or scaled correctly with different devices. 现在,按钮的位置无法与其他设备正确对齐或缩放。

I wrote the following code under iPhone 6 screen size. 我在iPhone 6屏幕尺寸下编写了以下代码。

UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [but setFrame:CGRectMake(605, 320, 35, 35)];
        [but setTitle:@"Login" forState:UIControlStateNormal];
        [but setExclusiveTouch:YES];
        [self.view addSubview:but];

If i want to have the same position for iPhone 6 plus as the iPhone 6. What can i do? 如果我想在iPhone 6 plus和iPhone 6上拥有相同的位置,该怎么办?

Many thanks. 非常感谢。

Use CGFloat screenScale = [[UIScreen mainScreen] scale]; 使用CGFloat screenScale = [[UIScreen mainScreen] scale]; . Now screenScale can be used to determine if it is a retina display, that is the current device scale. 现在,可以使用screenScale来确定它是否是视网膜显示,即当前的设备比例。

To get the current bounds of the screen: CGRect screenBounds = [[UIScreen mainScreen] bounds]; 获取屏幕的当前边界: CGRect screenBounds = [[UIScreen mainScreen] bounds];

To get the current pixel representation of the device, use CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale); 要获取设备的当前像素表示形式,请使用CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale); After this, it's a matter of using relative positioning, rather than absolute positioning which you are using now. 此后,只需使用相对定位即可,而不是现在使用的绝对定位。 That is, use all elements currently visible to determine the actual position of the button. 也就是说,使用当前可见的所有元素来确定按钮的实际位置。 For example CGFloat yPos = (screenSize.height-20) . 例如CGFloat yPos = (screenSize.height-20) yPos will now be relative to the bottom of the screen, minus 20 pixels on all devices. yPos现在将相对于屏幕底部,在所有设备上减20像素。

My suggestion is to use auto-layout though. 我的建议是使用自动布局。 There you can create constraints that are relative (or absolute if you want that, but it removes the purpose of auto-layout). 在这里,您可以创建相对的约束(如果需要,则可以是绝对约束,但是它消除了自动布局的目的)。 There are very good guides on the net just a short googling away. 网上搜寻非常不错的指南,仅需短暂搜索即可。

You can also set autoresizing mask to your UIButton . 您还可以将自动autoresizing mask设置为UIButton Check this link . 检查此链接 You need to set autoresizing mask for left margin , height and width of UIButton 您需要为UIButton的左边距,高度和宽度设置自动调整大小的蒙版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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