在我的视图控制器中,我有两个对象。TopView和CustomScrollview。我想将topiveie放在顶部,并在他们的下方定位customscrollview,所以我说:
// TOP VIEW LAYOUT
// horizontal
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:| [_topView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_topView, self)]];
// vertical
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_topView(89)]" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_topView, self)]];
// CUSTOMSCROLLVIEW
// horizontal
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_customScrollVeiw]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_customScrollVeiw, self)]];
// vertical
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_topView]-(0)-[_customScrollVeiw]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_customScrollVeiw, _topView, self)]];
效果很好。
,但是现在我想在CustomScrollview滚动时移动顶视图,因此我创建此功能:
- (void) moveOnScroll: (CGPoint) offset contentSize: (CGSize) contentSize
{
float delta = offset.y - self.yPosition;
if (self.yPosition > offset.y) {
if (labs(self.frame.origin.y) < self.frame.size.height/50 ){
self.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
else if (self.frame.origin.y - delta < 0 && offset.y < (contentSize.height - self.screenHeight)){
self.frame = CGRectMake(0, self.frame.origin.y - delta, self.frame.size.width, self.frame.size.height);
}
else{
self.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}
}
else {
if (self.frame.origin.y > (- self.frame.size.height + self.labelHeight) && offset.y > 0){
if (self.frame.origin.y - delta < (- self.frame.size.height + self.labelHeight )) {
self.frame = CGRectMake(0, (- self.frame.size.height + self.labelHeight ), self.frame.size.width, self.frame.size.height);
}
else{
self.frame = CGRectMake(0, self.frame.origin.y - delta , self.frame.size.width, self.frame.size.height);
}
}
}
self.yPosition = offset.y;
}
现在,当我滚动时,TopView正在隐藏,但是CustomScrollview不再拥抱TopView,它一直保持在他的位置,并且不会移动。(v:[_ topview] - (0) - [_ CustomScrollveiw] |)
如何解决此问题?
在视图控制器中的某个地方保存此约束
// vertical
NSArray *topViewContstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_topView(89)]" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_topView, self)]
for (NSLayoutConstraint *constraint in topViewContstraints) {
if (constraint.firstAttribute == NSLayoutAttributeHeight) {
_topViewConstraint = constraint;
break;
}
}
[self.view addConstraints:topViewContstraints];
然后通过保存的约束更改顶视图的位置:
_topViewConstraint.constant = yOffset;
yoffset在您的自定义方法中计算的值。
哦,您将需要动画此更改:
[UIView animateWithDuration:0.3 animations:^{
[_topView layoutIfNeeded];
}];