如何使用autolayout使视图浮动在滚动视图上

时间:2013-02-17 23:51:35

标签: ios ios6

iOS 6.0 Release notes中有以下声明:

  

请注意,您可以使滚动视图的子视图显示为浮动   (不滚动)通过创建约束来覆盖其他滚动内容   在视图和滚动视图的子树之外的视图之间,例如   滚动视图的超级视图。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:3)

我做了一些游戏,我有一个很好的例子。

视图不会滚动,它会放在顶部,其高度是scrollview hight和任意值之间的差异。

// in viewDidLoad

UIIView *myView = [[UIView alloc] init];
[self.scrollView addSubview:myView];
myView.translatesAutoresizingMaskIntoConstraints = NO;

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.mapView 
    attribute:NSLayoutAttributeTop 
    relatedBy:(NSLayoutRelationEqual) 
       toItem:self.containerView 
    attribute:(NSLayoutAttributeTop) 
   multiplier:1.0 
     constant:0];
[self.view addConstraint:constraint];


// Give my view some intrinsic size
NSDictionary *dict = NSDictionaryOfVariableBindings(myView);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|[myView]|" 
                                                               options:(NSLayoutFormatAlignAllBaseline) 
                                                               metrics:nil 
                                                                 views:dict];
[self.view addConstraints:constraints];

// In view did appear

// calc height from height of scroll view - this is needs work
float height = -self.scrollView.frame.size.height + 250;

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.mapView                attribute:NSLayoutAttributeHeight 
    relatedBy:(NSLayoutRelationEqual) 
       toItem:self.containerView 
    attribute:(NSLayoutAttributeHeight) 
       multiplier:1.0 
     constant:offset];
[self.view addConstraint:constraint];