0

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.

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?

Many thanks.

Clarence
  • 1,951
  • 2
  • 34
  • 49
  • use auto layout and add constrains to it or give width,hight and x,y relative to bound in % [link](http://matthewmorey.com/creating-uiviews-programmatically-with-auto-layout/) this link might help you – Jignesh Agola Dec 01 '14 at 09:56

2 Answers2

1

Use CGFloat screenScale = [[UIScreen mainScreen] scale];. Now screenScale can be used to determine if it is a retina display, that is the current device scale.

To get the current bounds of the screen: 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); 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). yPos will now be relative to the bottom of the screen, minus 20 pixels on all devices.

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.

Widerberg
  • 1,118
  • 1
  • 10
  • 24
  • Hi Alexander, thank you for you answers. But my problem is that i have many buttons on a view with irregular arrangement. It was so difficult for me to align them using Autolayout. Could you please tell me more about the code? I still can't get this working. Thanks – Clarence Dec 01 '14 at 14:56
1

You can also set autoresizing mask to your UIButton. Check this link. You need to set autoresizing mask for left margin , height and width of UIButton

Community
  • 1
  • 1
Sushil Sharma
  • 2,321
  • 3
  • 29
  • 49