【问题标题】:Button with different width on iPhone 5iPhone 5上不同宽度的按钮
【发布时间】:2013-03-28 17:12:18
【问题描述】:

如果用户使用的是 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)];

【问题讨论】:

    标签: ios objective-c iphone-5


    【解决方案1】:

    您正在使用超出其范围的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
    • 哇!!你解决了我的问题,但请注意 varWidth 必须以 '.0' 结尾
    • @Maarten1909 因为你必须把varWidth 当作float 而不是integer
    【解决方案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)];
        }
    }
    

    【讨论】:

    • 因为我有不止一个按钮,这种方式确实有效,但我的代码会变得非常混乱
    • 看看修改后的代码...这样可以添加更多按钮,如果你需要改变宽度,你只需要编辑一个地方,#define
    • 不过,如果有 10 个按钮,这意味着有 20 个 setFrame: 行而不是 10 个,或者如果有一个单独的 iPad 部分,则为 30 个......并且更改按钮的位置需要编辑每个 @987654324 @单独调用按钮。
    【解决方案3】:

    检查设备的最佳和快捷方式是iPhone 5 or iPhone5 < (Less Then)。 为此,您需要在项目的.pch 文件中编写以下代码。

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

    这个 Like 检查设备,是不是 iPhone5。

    你只需要写一个条件来管理它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      相关资源
      最近更新 更多