当定向发生时,如何刷新 UIView



我的代码是这样的:

- (void)viewDidLoad
{
  [self setGridView];
}
-(void)setGridView
{
  CGRect frame; 
  frame .origin.x=0;
  frame.origin.y=20;
  frame.size.width=GRID_WEIGHT;
  frame.size.height=GRID_HEIGHT;
  GridView *ObjGridView=[[GridView alloc]initWithFrame:frame]; 
  [[NSBundle mainBundle ] loadNibNamed:@"GridView" owner:ObjGridView options:nil];
  [ObjGridView setGridViewFrame:frame];
  [self.view addSubview:ObjGridView.GridCellView];
  frame .origin.x+=GRID_WEIGHT;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  return YES;
}

此代码向视图添加子视图并设置框架

我的问题:1-当方向(横向或纵向)发生时如何刷新我的视图,因为我在 LanView 模式下设置了子视图的框架,并且我还想在我的纵向视图中使用理智视图。(基本上我在哪里称呼这个 -(void)setGridView 委托方法)?

2-我怎么知道,我的子视图超出了视图的边界,以便我可以在我的setGridView方法中处理子视图?

1.当您的方向发生变化时,下面的方法将自动调用。根据每个方向进行必要的更改。

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if (interfaceOrientation == UIInterfaceOrientationPortrait) {}
else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {} 
else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {} 
else if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {}
return YES;
}

2.您应该知道视图的宽度和高度,并相应地设置框架。这没什么大不了的。

希望这是有帮助的。

我自己正在学习iOS应用程序开发的来龙去脉,所以请原谅我的简短回答。

我相信您可以在 Apple 开发人员资源本文档中标题为"响应方向更改"的部分中找到问题的答案:

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/RespondingtoDeviceOrientationChanges/RespondingtoDeviceOrientationChanges.html

我希望这可以帮助您推断出问题的解决方案。

In viewDidLoad

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

通知您方向已更改的方法:-

-(void)OrientationChange:(NSNotification*)notification
{
    UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];
    if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight)
    {
        NSLog(@"Landscape");
    }
    else if(Orientation==UIDeviceOrientationPortrait)
    {
        NSLog(@"Portrait");
    }
}

回答您的问题L

关于在方向变化时调整大小:如果您相应地设置弹簧和支柱,它应该会自动调整大小,或者您可以根据 deamonsarea 的答案在代码中执行此操作

要检查视图是否超出了超级视图的边界,请使用 CGRectContainsRect类似的东西。

CGRect frame0 = self.view.bounds;
CGRect frame1 = ObjGridView.frame;
if(CGRectContainsRect(frame0,frame1)==NO){
  NSLog(@"exceeds bounds")
}

还注意到您没有调用[super viewDidLoad]和此行

[[NSBundle mainBundle ] loadNibNamed:@"GridView" owner:ObjGridView options:nil];

加载视图的新实例,但您没有在任何地方引用它

我在寻找一种对 UIView 本身内部的方向变化做出反应的方法时发现了这个问题。万一其他人来了...

如果要对UIView内的方向更改做出反应,而不是对UIViewController(出于封装或其他原因),可以使用此方法:

class MyView: UIView {
  override func layoutSubviews() {
    super.layoutSubviews()
    println("orientation or other bounds-impacting change")
  }
}

最新更新