2013-11-01 4 views
1

У меня есть UIScrollView, который может иметь виды контента различной высоты. Если содержимое меньше, чем scrollView, я хочу, чтобы контент был по центру по вертикали. Однако, когда контент больше, я хочу, чтобы он придерживался вершины.Центр или вывод к началу страницы с использованием автозапуска

Можно ли это сделать с помощью автоматической компоновки?

ответ

1

Просто получил это, чтобы работать, может быть лучший способ, но это, похоже, работает нормально.

  1. Настройте представление содержимого в прокрутке, как показано ниже. enter image description here

  2. Добавить IBOutlets для 3 ограничений, вертикальное пространство сверху, вертикальное пространство внизу, а затем высота представления контента.

3. ` - (Недействительными) 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]; 

} `

+0

Спасибо, это полезно! – Voxar

2

Я обнаружил, что вы можете установить одно ограничение, которое центрирует вид, а затем ограничение с более высоким приоритетом, который гласит, что верхняя часть содержимого может быть больше 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]]; 
Смежные вопросы