2014-01-21 4 views
2

Я был поиск высоким и низким, чтобы попытаться понять это, надеюсь, кто-то может помочь (я думаю, что это, вероятно, довольно тривиально, но я как раз над запутанной ситуации!)Встраивание вид контейнера в UIScrollView

I используя XCode 5 и раскадровки. У меня есть вид контейнера, который занимает около 75% пространства экрана на iPhone. Над этим у меня есть несколько кнопок (и другие виджеты). Я хочу иметь возможность загружать в контроллер представления в контейнер при нажатии одной из кнопок.

Пока все это работает нормально, но диспетчеры просмотра, которые загружаются, имеют разные размеры и могут измениться в будущем. Я хотел бы иметь возможность прокручивать просмотр ребенка (произвольного размера).

Я попытался вставить контейнер в виде прокрутки, но затем, как часть процесса добавления нового дочернего представления, вы должны установить размер кадра, но я хочу, чтобы ребенок понял, насколько он должен быть, а затем установить все соответственно.

Я не совсем уверен, что лучший способ пойти об это (или установка ограничений в раскадровку или программно?)

Любой совет будет здорово! Или ссылка на учебник была бы очень полезной, единственными, которые я мог найти, были добавление контроллеров представлений в представление контейнера или добавление представлений в прокрутку, ни одна из которых, похоже, не работает так, как ожидалось, с Xcode 5 (iOS 7)

Спасибо!

-Edit-

Вот код, который я использовал, чтобы представить контроллер представления детали произвольного размера, остальное все готово в раскадровке (только в случае, если это полезно для тех, кто в будущем!) Это теперь работает:

- (void)presentDetailController:(UIViewController*)detailVC{ 

//0. Remove the current Detail View Controller shown 
if(self.currentDetailViewController){ 
    [self removeCurrentDetailViewController]; 
} 

//1. Add the detail controller as child of the container 
[self addChildViewController:detailVC]; 

//2. DO NOT Define the detail controller's view size 
//detailVC.view.frame = [self frameForDetailController]; 

//3. Add the Detail controller's view to the Container's detail view and save a reference to the detail View Controller 
[self.detailView addSubview:detailVC.view]; 
self.currentDetailViewController = detailVC; 

// Pin the height to the container to make it scrollable? 
[self.detailView addConstraint:[NSLayoutConstraint constraintWithItem:self.detailView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0f constant:detailVC.view.bounds.size.height]]; 

//4. Complete the add flow calling the function didMoveToParentViewController 
[detailVC didMoveToParentViewController:self]; 

} 

ответ

1

Вы можете установить ограничения в любом месте и правильно работать. Секрет заключается в следующем: вы должны установить ограничения вида контейнера на верхний, левый, нижний и правый прокрутки, содержащие его. Затем Autolayout рассчитает размер содержимого прокрутки в соответствии с тем, что находится внутри представления контейнера.

См. Раздел под названием Pure Auto Layout Approach в примечаниях к выпуску iOS 6. Там даже есть пример кода.

// parentView is the thing you want to add the scroll view to 


// setup the scroll view, and add it to the parent view 
UIScrollView* scrollView = [[UIScrollView alloc] init]; 
scrollView.backgroundColor = [UIColor colorWithWhite:0.9f alpha:1.0f]; 

[parentView addSubview:scrollView]; 

scrollView.translatesAutoresizingMaskIntoConstraints = NO; 

NSDictionary* views = NSDictionaryOfVariableBindings(scrollView); 

[parentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics:nil views:views]]; 
[parentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]|" options:0 metrics:nil views:views]]; 


// set up the content 
UILabel* firstLongLabel = [[UILabel alloc] init]; 
firstLongLabel.numberOfLines = 0; 
firstLongLabel.text = @" Four score and seven years ago our fathers brought forth, on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.\n\nNow we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live. It is altogether fitting and proper that we should do this."; 
firstLongLabel.backgroundColor = [UIColor greenColor]; 

UIButton* middleButton = [UIButton buttonWithType:UIButtonTypeSystem]; 
[middleButton setTitle:@"Middle Button" forState:UIControlStateNormal]; 
middleButton.backgroundColor = [UIColor purpleColor]; 

UILabel* lastLongLabel = [[UILabel alloc] init]; 
lastLongLabel.numberOfLines = 0; 
lastLongLabel.text = @"But, in a larger sense, we can not dedicate, we can not consecrate – we can not hallow – this ground. The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us – that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion - that we here highly resolve that these dead shall not have died in vain – that this nation, under God, shall have a new birth of freedom, and that government of the people, by the people, for the people, shall not perish from the earth."; 
lastLongLabel.backgroundColor = [UIColor yellowColor]; 


// now create a content view and add all of our previously created content to it 
UIView* contentView = [[UIView alloc] init]; 
contentView.backgroundColor = [UIColor blueColor]; 

[contentView addSubview:firstLongLabel]; 
[contentView addSubview:middleButton]; 
[contentView addSubview:lastLongLabel]; 

[scrollView addSubview:contentView]; 


// and now comes the important part.. the constraints 
firstLongLabel.translatesAutoresizingMaskIntoConstraints = middleButton.translatesAutoresizingMaskIntoConstraints = lastLongLabel.translatesAutoresizingMaskIntoConstraints = contentView.translatesAutoresizingMaskIntoConstraints = NO; 

views = NSDictionaryOfVariableBindings(firstLongLabel, middleButton, lastLongLabel, contentView); 

// first, add constraints dealing with the content inside the content view 
// these are simple and should be easily understood 
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[firstLongLabel]-10-|" options:0 metrics:nil views:views]]; 
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[middleButton]-10-|" options:0 metrics:nil views:views]]; 
[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[lastLongLabel]-10-|" options:0 metrics:nil views:views]]; 

[contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[firstLongLabel]-10-[middleButton]-10-[lastLongLabel]-10-|" options:0 metrics:nil views:views]]; 

// then add constraints dealing with the content view that we put into the scroll view... 
// the trick here is that we lock the content to only partially the width 
// of the scroll view's parent. if we don't do that, then the labels will force the scroll 
// view to expand horizontally instead of vertically. 
// 
// as an exercise, you can try locking the left and right to the scroll view instead of the parent view to see what happens 
[parentView addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeLeft multiplier:1 constant:10]]; 
[parentView addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:parentView attribute:NSLayoutAttributeRight multiplier:1 constant:-10]]; 

// by locking the content view's vertical edges to that of the scroll view, it'll cause the 
// scroll view to expand vertically to accomodate the entire content view 
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[contentView]-10-|" options:0 metrics:nil views:views]]; 
+0

Спасибо, я уже пробовал этот подход, но не смог заставить его работать (просмотр прокрутки просто не прокручивался). Как вы собираетесь настраивать рамку представления контейнера и дочернего элемента при загрузке нового представления контроллера представления? – user2851943

+0

Вы разрешаете автомасштабирование делать это за вас. Я попытаюсь привести пример. – Travis

+0

Пример был бы потрясающим! Спасибо огромное! – user2851943

Смежные вопросы