如何使用CGRectMake修复不同设备大小的按钮位置

时间:2016-06-20 04:44:20

标签: ios uibutton cgrectmake

这里我使用CGRectMake创建了一个UIButton,这个按钮看起来非常适合纵向模式,并且保持固定在我想要的相同位置。但是,当我将方向更改为横向按钮位置更改时。我怎样才能解决这个问题。

 UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(216, 130, 64, 30)];
[button addTarget:self action:@selector(yourEditButtonClicked:) forControlEvents:UIControlEventTouchUpInside];     button.tag = indexPath.row;
[button setImage:[UIImage imageNamed:@"btn-details.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:button];

NSLog(@"sender.tag cell is%ld ",(long)button.tag);

2 个答案:

答案 0 :(得分:1)

定义如下的宏

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
#define SCREEN_MAX_LENGTH (MAX(SCREEN_WIDTH, SCREEN_HEIGHT))
#define SCREEN_MIN_LENGTH (MIN(SCREEN_WIDTH, SCREEN_HEIGHT))

#define IS_IPHONE_4_OR_LESS (IS_IPHONE && SCREEN_MAX_LENGTH < 568.0)
#define IS_IPHONE_5 (IS_IPHONE && SCREEN_MAX_LENGTH == 568.0)
#define IS_IPHONE_6 (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0)
#define IS_IPHONE_6P (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0)

在你的xib中,拖动按钮并将其放在xib中。调整xib的屏幕宽度和高度,并根据各种屏幕宽度和高度定位按钮。请注意各种屏幕尺寸的宽度,高度,x,y位置,然后在以下代码中使用它们

 UIButton *button;
//use x,y,width,height values relative to the values you have noted previously and  pass them in  the following parameters

       if (IS_IPHONE_4_OR_LESS || IS_IPHONE_5)
        {
         button =[[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];   
        }
        else if (IS_IPHONE_6)
        {
         button =[[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];   

        }
        else if (IS_IPHONE_6P)
        {
         button =[[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];   

        }


[button addTarget:self action:@selector(yourEditButtonClicked:) forControlEvents:UIControlEventTouchUpInside];     button.tag = indexPath.row;
[button setImage:[UIImage imageNamed:@"btn-details.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:button];

NSLog(@"sender.tag cell is%ld ",(long)button.tag);

答案 1 :(得分:1)

将垂直/水平约束应用于位置0处设置的按钮。然后单击约束并调整乘数(在0-2范围内),将视图按比例放置在超视图上/跨越超视图。