当对象不可见时更改布局

时间:2013-08-19 11:46:40

标签: ios objective-c cocoa-touch ios5

屏幕上有4个对象:( UIView或UIButton)

A B C D

在某些情况下,我需要隐藏其中一个或多个会导致此问题:

A   C D 

或者这个:

A     D

在iOS 5中是否有办法(无法使用AutoLayout )(除了使用大量 ifs 并以编程方式设置位置)空格并强制上面的例子看起来像这样:

A C D
 A D

1 个答案:

答案 0 :(得分:0)

我用KVO来实现这个目标 第1步:注册ViewController作为观察者,以便在所有视图中更改隐藏属性。

[_view1 addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
[_view2 addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
[_view3 addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
[_view4 addObserver:self forKeyPath:@"hidden" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

第2步:添加方法以响应ViewController

中的更改通知
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
  if(![object isEqual:[viewArray lastObject]]){
    UIView *viewToHide = (UIView *)object;
    CGRect newFrame = viewToHide.frame;
    CGRect oldFrame;
    int indexOfObject = [viewArray indexOfObject:object];
    for(int i = indexOfObject + 1; i < viewArray.count; i++){
      UIView *viewToChange = [viewArray objectAtIndex:i];
      if(viewToChange.hidden){
        continue;
      }
      else{
      oldFrame = viewToChange.frame;
      viewToChange.frame = newFrame;
      [viewArray replaceObjectAtIndex:i withObject:viewToChange];
      newFrame = oldFrame;
      }
    }
  }
}

第3步:我在点击它们时隐藏了视图。你当然可以以任何你想要的方式实现这一目标。

- (IBAction)viewTapped :(UIGestureRecognizer *)recogniser{
  CGPoint touchPoint = [recogniser locationInView:self.view];
  UIView *touchView = [self.view hitTest:touchPoint withEvent:nil];
  if([touchView isKindOfClass:[UIView class]]){
    touchView.hidden = YES;
  }
}