How can I fix button position for different Device Size Using CGRectMake

180 Views Asked by At

I have created a UIButton using CGRectMake, This button looks perfect for the portrait mode and remains fixed in the same place as I wanted. But, when I change the orientation to landscape button position changes. How can I fix this?

 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

There are 2 best solutions below

1
AudioBubble On

Define macros like the following,

#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)

In your xib, drag button and put it inside the xib. Resize the screen width and height of xib and position your button for various of various screen width and height.Note down the width , height, x,y positions for various screen sizes and then use them in your following code

 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);
0
Tim On

Apply vertical/horizontal constraints to the button set at position 0. Then click the constraints and adjust the multiplier (in the range 0-2) which places the view proportionally down/across the superview.