我有一个 UIScrollView 可以有不同高度的内容视图。如果内容小于滚动视图,我希望内容垂直居中。但是,当内容较大时,我希望它保持在顶部。
这可以使用自动布局来实现吗?
我有一个 UIScrollView 可以有不同高度的内容视图。如果内容小于滚动视图,我希望内容垂直居中。但是,当内容较大时,我希望它保持在顶部。
这可以使用自动布局来实现吗?
我发现您可以设置一个使视图居中的约束,然后设置一个具有更高优先级的约束,即内容顶部只能大于 0。
// If the content is smaller than the scrollview then center it, else lock to top
NSLayoutConstraint *centerYConstraint = [NSLayoutConstraint constraintWithItem:self.contentController.view
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:_scrollView
attribute:NSLayoutAttributeCenterY
multiplier:1 constant:0];
// Constrain the top to not be smaller than 0 (multiplier:0)
NSLayoutConstraint *lockToTopConstraint = [NSLayoutConstraint constraintWithItem:self.contentController.view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:_scrollView
attribute:NSLayoutAttributeTop
multiplier:0 constant:0];
//It't more important that the content doesn't go over the top than that it is centered
centerYConstraint.priority = UILayoutPriorityDefaultLow;
lockToTopConstraint.priority = UILayoutPriorityDefaultHigh;
[self.view addConstraints:@[centerYConstraint, lockToTopConstraint]];
Just got this to work, there may be a better way but this seems to work just fine.
Set up the content view in the scroll view like I did below.
Add IBOutlets for 3 constraints, the VerticalSpace on the top, the vertical space on the bottom, and then the content view's height.
3. ` -(void)adjustContentSize {
self.contentHeight.constant = 1000; //I tried out different values here to make sure it'd work for whatever size you need.
if (self.contentHeight.constant > self.view.frame.size.height)
{
self.contentVerticalSpaceTop.constant = 0; //This will ensure it sticks to the top if it's bigger than the frame
}else
{
self.contentVerticalSpaceTop.constant = ((self.view.frame.size.height/2)-(self.contentHeight.constant/2));
}
self.contentBottomVerticalSpace.constant = self.contentVerticalSpaceTop.constant; //setting the bottom constraint's constant to the top's will ensure that the content's centered vertically
[self.view layoutIfNeeded];
} `