UIButton根据方向定位

时间:2011-11-28 02:01:02

标签: iphone ipad ios4 ios5

我已通过以下方式在iPhone视图上创建了许多按钮

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];

button1.frame = CGRectMake(1.0, 35.0, 100.0, 100.0);   
[button1 setTitle:NSLocalizedString(@"Button1", @"") forState:UIControlStateNormal];

等...

因为我没有使用界面构建器,所以在方向更改时我无法控制按钮位置。 有没有办法在我旋转iPhone时,按钮移动到不同的坐标?

例如,如果iphone是肖像我希望它们是

button1.frame = CGRectMake(1.0, 35.0, 100.0, 100.0); 

如果它是风景我希望它们是

button1.frame = CGRectMake(1.0, 105.0, 100.0, 100.0); 

但我也希望这是动态的,而不仅仅是在开始时找到iphone的方向。因此,如果我在程序加载后旋转iphone,效果也会发生!

非常感谢

2 个答案:

答案 0 :(得分:4)

你所要做的就是实现旋转或旋转:

  

回应查看轮换事件

     

-willRotateToInterfaceOrientation:持续时间:

     

-didRotateFromInterfaceOrientation:

示例:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    if(UIInterfaceOrientation == UIInterfaceOrientationLandscape){
        //Behavior for landscape orientation

    }
}

另外一定要实施:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

返回YES以获取界面中所有允许的方向。

答案 1 :(得分:4)

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // Set y depend on interface orientation
    CGFloat originInY = ((toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)  ? 105.0f : 35.0f;

    // Set the button's y offset
    button.frame = CGRectMake(button.frame.origin.x, originInY, button.frame.size.width, button.frame.size.height);
}

我认为它本身会动画,如果没有,你可以使用UIView animation


编辑如何实现此方法(仅基于您提供的代码):
请注意,您应该将button1设置为.h文件中的instance variable,而不是{。strong>中的local variable

.h:

@interface MenuViewController : UIViewController
{
  UIButton * _button1;
}

// your methors

@property (nonatomic, retain) UIButton * button1;

@end

.m:

#import "MenuViewController.h"

@implementation MenuViewController

@synthesize button1 = _button1;

- (void)viewDidLoad
{
  [super viewDidLoad];
  //UIButton button1 = [UIButton buttonWithType:UIButtonTypeCustom];
  self.button1 = [[UIButton alloc] initWithFrame:CGRectMake(1.0, 35.0, 100.0, 100.0)];
  [self.view addSubview:button1];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOr‌​ientation      
{
  return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // Set y depend on interface orientation
    CGFloat originInY = ((toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)  ? 105.0f : 35.0f;

    // Set the button's y offset
    [self.button1 setFrame:CGRectMake(self.button1.frame.origin.x, originInY, self.button1.frame.size.width, self.button1.frame.size.height)];
}

// other methods include dealloc.

@end