How to make a view float over a scroll view using

2019-07-04 03:51发布

问题:

In the iOS 6.0 Release notes there is the following statement:

Note that you can make a subview of the scroll view appear to float (not scroll) over the other scrolling content by creating constraints between the view and a view outside the scroll view’s subtree, such as the scroll view’s superview.

Anyone have any ideas?

回答1:

I did some playing around and I have a working example of sorts.

The view does not scroll, it gets put at the top, with a height that is the difference between the scrollview hight and an arbitrary value.

// 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];


标签: ios ios6