iPhone 5上不同宽度的按钮

3

如果用户使用的是iPhone 5,我希望增加自定义按钮的大小。

这是我在.m文件中的代码:

//.m File
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
        int varWidth = 228;
    }
    if(result.height == 568)
    {
        int varWidth = 272;
    }
}

....

[newButton setFrame:CGRectMake(8.0, 40.0, 228, 80.0)];

但我想要像这样的东西:
[newButton setFrame:CGRectMake(8.0, 40.0, varWidth, 80.0)];
3个回答

4
您正在超出 varWidth 的作用域使用它。
int varWidth;

if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
        varWidth = 228;
    }
    if(result.height == 568)
    {
        varWidth = 272;
    }
}

....

[newButton setFrame:CGRectMake(8.0, 40.0, varWidth, 80.0)];

在这种情况下,按钮的宽度始终为228,但如果用户有iPhone 5,则我希望它为272。 - Berendschot
1
哇!!你解决了我的问题,但请注意varWidth必须以'.0'结尾。 - Berendschot
@Maarten1909 你需要将 varWidth 定义为 float 而不是 integer - Baby Groot

2
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
       [newButton setFrame:CGRectMake(8.0, 40.0, 228.0, 80.0)];
    }
    if(result.height == 568)
    {
       [newButton setFrame:CGRectMake(8.0, 40.0, 272, 80.0)];
    }
}

为什么不这样做呢?

另一个建议:

使用 #define。

例如:

#define iPhone5width 272
#define iPhone4width 228

if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
       [newButton setFrame:CGRectMake(8.0, 40.0, iPhone4width, 80.0)];
    }
    if(result.height == 568)
    {
       [newButton setFrame:CGRectMake(8.0, 40.0, iPhone5width, 80.0)];
    }
}

因为我有多个按钮,这种方法虽然可行,但我的代码会变得非常混乱。 - Berendschot
看一下修改后的代码...这样,可以添加更多的按钮,如果需要更改宽度,只需编辑一个地方,即 #define。 - lakshmen
然而,如果有10个按钮,这意味着需要20个setFrame:行而不是10个,如果有一个单独的iPad部分,则需要30个。而且更改按钮的位置需要单独编辑每个按钮的setFrame:调用。 - Arkku

1

检查设备是否为 iPhone 5 或 iPhone5 < (小于) 的最佳和简短方法。 要获取此内容,您需要在项目的 .pch 文件中编写以下代码。

#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

这是一个类似的检测设备,用于判断是否为iPhone5。

您只需要编写一个条件来管理它。

if( IS_IPHONE_5 )
        // set or put code related to iPhone 5.
else
        // set or put code related to less then iPhone 5.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接