2015-10-09 2 views
0

------------- Навигация -----------UISplitView с заголовком программно быстро

------------- Дополнительный вид ------------

--Master View-- | --detail View--

Смотреть изображение: Layout

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

В течение UINavigationController, я хочу, чтобы содержать UISplitViewController, и выше, что UISplitController я хочу вид заголовка, который простирается на обоих Мастеров и Detail контроллеров представления.

В этом представлении я создам панель поиска с расширенными параметрами поиска. Я хочу, чтобы иметь возможность редактировать высоту этого дополнительного вида, чтобы он мог эффективно нажимать UISplitViewController.

Каков наилучший способ достижения этого программно? Это то, что я должен делать с помощью контейнеров (они на самом деле не то, что я когда-либо использовал раньше)?

Благодаря

ответ

0

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

В этом UIViewController добавьте представление, прикрепленное к вершине, начало и конец и придайте ему высоту. Это ваша область поиска на диаграмме.

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

Добавить свой UISplitViewController в качестве дочернего контроллера этого вида контейнера.

Это дает вам то, что у вас есть на диаграмме.

Это очень просто сделать в раскадровке за считанные минуты. Чтобы сделать это в коде, вам нужно будет посмотреть документацию о том, как добавить дочерний контроллер. https://developer.apple.com/library/prerelease/ios/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html

Update: Попробуйте следующий код в вас UIViewController:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Create top and bottom views 
    UIView *topView=[[UIView alloc] init]; 
    UIView *bottomView=[[UIView alloc] init]; 

    // Stop constraints being auto generatyed. 
    [topView setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    [bottomView setTranslatesAutoresizingMaskIntoConstraints:NO]; 

    // Set the colors so we can see the views. 
    [topView setBackgroundColor:[UIColor redColor]]; 
    [bottomView setBackgroundColor:[UIColor blueColor]]; 

    // Add the two views 
    [self.view addSubview:topView]; 
    [self.view addSubview:bottomView]; 

    // 
    // Add constraints. 
    // 

    // Constraint dictionary 
    NSMutableDictionary *viewDictionary=[NSMutableDictionary dictionaryWithObjectsAndKeys:topView, @"topView",bottomView,@"bottomView", nil]; 

    NSLayoutFormatOptions options; 

    // Pin leading and trailing of top view 
    NSArray *constraints= 
     [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[topView]|" 
               options:options 
               metrics:nil 
                views:viewDictionary 
     ]; 
    [self.view addConstraints:constraints]; 

    // Pin leading and trailing of bottom view 
    constraints= 
    [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[bottomView]|" 
              options:options 
              metrics:nil 
               views:viewDictionary 
    ]; 
    [self.view addConstraints:constraints]; 

    // Pin top view to top, give it height 100, pin bottom to bottom view and bottom 
    // view to bottom. 
    constraints= 
    [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topView(100)][bottomView]|" 
              options:options 
              metrics:nil 
               views:viewDictionary 
    ]; 
    [self.view addConstraints:constraints]; 

    // 
    // Add Split View Controller as child. 
    // 

    // Left hand split view controller Temp for now. 
    UIViewController *left=[[UIViewController alloc] init]; 
    left.view.backgroundColor = [UIColor orangeColor]; 

    // Right hand split view detail contreoller. Temp for now. 
    UIViewController *right=[[UIViewController alloc] init]; 
    right.view.backgroundColor = [UIColor greenColor]; 

    // Create split view with left and right 
    UISplitViewController *splitView=[[UISplitViewController alloc] init]; 
    [email protected][left,right]; 

    // Add as a child controller to the bottom view 
    [self addChildViewController:splitView]; 
    [bottomView addSubview:splitView.view]; 

    // Add constraints for split view. 
    viewDictionary=[NSMutableDictionary dictionaryWithObjectsAndKeys:splitView.view, 
        @"splitView",nil]; 

    // Pin all sides to the container. 
    constraints= 
     [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[splitView]|" 
               options:options 
               metrics:nil 
                views:viewDictionary 
     ]; 
    [bottomView addConstraints:constraints]; 

    constraints= 
     [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[splitView]|" 
               options:options 
               metrics:nil 
                views:viewDictionary 
    ]; 
    [bottomView addConstraints:constraints]; 

    // Complete contract for adding child controller. 
    [splitView didMoveToParentViewController:self]; 
} 
+0

Thanks Rory, что помогает. Я, вероятно, в конечном итоге сделаю это в раскадровке, но если бы я сделал это программно. Я счастлив создать UINavigationController, добавив UIViewController и добавив представление. Я не уверен, что понимаю, как вы создаете контейнерный вид программно? Это так же просто, как использование addChildViewController внутри UIViewController, добавленного выше? –

+0

Для просмотра контейнера программно, я думаю, вы просто создаете обычный UIView с ограничениями, привязывающими его туда, где вы этого хотите. В раскадровке есть отдельное представление о работе. Затем следуйте инструкциям в ссылке, которую я отвечу: добавьте дочерний контроллер к главному контроллеру, установите рамку дочерних контроллеров в рамку просмотра контейнера, добавьте представление дочерних контроллеров в представление контейнера в качестве подсмотра и затем, наконец, didMoveToParentViewController' для ребенка. Вы можете добавить ограничения для представления дочерних контроллеров после их добавления. –

+0

Спасибо, Рори. Я пытался сделать это часами, и мне не повезло. Я не думаю, что у вас есть пример кода? Я хочу сделать это программно, поэтому я абсолютно понимаю каждый шаг, который предпринимается. Я создаю UIViewController, который находится внутри UINavigationController, это нормально. Затем я добавил представление к контроллеру представления с помощью VC.view.addview (topView), но как я могу добавить нижний вид? Спасибо за вашу помощь. –

0

Благодаря Рори:

let topView = UIView() 
let bottomView = UIView() 

topView.setTranslatesAutoresizingMaskIntoConstraints(false) 
bottomView.setTranslatesAutoresizingMaskIntoConstraints(false) 

topView.backgroundColor = UIColor.redColor() 
bottomView.backgroundColor = UIColor.blueColor() 

self.view.addSubview(topView) 
self.view.addSubview(bottomView) 

var viewDictionary = Dictionary(dictionaryLiteral: ("topView", topView),("bottomView", bottomView)) 

var options = NSLayoutFormatOptions() 

var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[topView]|", options: nil, metrics: nil, views: viewDictionary) 

self.view.addConstraints(constraints) 

constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[bottomView]|", options: nil, metrics: nil, views: viewDictionary) 

self.view.addConstraints(constraints) 

constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topView(100)][bottomView]|", options: nil, metrics: nil, views: viewDictionary) 

self.view.addConstraints(constraints) 

let left = UIViewController() 
left.view.backgroundColor = UIColor.orangeColor() 

let right = UIViewController() 
right.view.backgroundColor = UIColor.greenColor() 

let splitView = UISplitViewController() 

splitView.viewControllers = [left, right] 

self.addChildViewController(splitView) 
bottomView.addSubview(splitView.view) 

viewDictionary = Dictionary(dictionaryLiteral: ("splitView", splitView.view)) 

constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[splitView]|", options: options, metrics: nil, views: viewDictionary) 

bottomView.addConstraints(constraints) 

constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[splitView]|",options: options, metrics: nil, views: viewDictionary) 

bottomView.addConstraints(constraints) 
splitView.didMoveToParentViewController(self) 

// Я получаю эту ошибку сейчас какой-то причине.

2015-10-12 18:20:13.417 GPSApp[36430:478129] Unable to simultaneously satisfy constraints. 
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7981a8c0 H:|-(0)-[UILayoutContainerView:0x7981c100] (Names: '|':UIView:0x7983e5e0)>", 
    "<NSLayoutConstraint:0x7981a860 H:[UILayoutContainerView:0x7981c100]-(0)-| (Names: '|':UIView:0x7983e5e0)>", 
    "<NSAutoresizingMaskLayoutConstraint:0x79815350 h=-&- v=-&- UILayoutContainerView:0x7981c100.midX == UIView:0x7983e5e0.midX + 512>" 
) 

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7981a860 H:[UILayoutContainerView:0x7981c100]-(0)-| (Names: '|':UIView:0x7983e5e0)> 

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. 
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 
2015-10-12 18:20:13.419 GPSApp[36430:478129] Unable to simultaneously satisfy constraints. 
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7981a270 V:|-(0)-[UILayoutContainerView:0x7981c100] (Names: '|':UIView:0x7983e5e0)>", 
    "<NSLayoutConstraint:0x7981a220 V:[UILayoutContainerView:0x7981c100]-(0)-| (Names: '|':UIView:0x7983e5e0)>", 
    "<NSAutoresizingMaskLayoutConstraint:0x798153b0 h=-&- v=-&- UILayoutContainerView:0x7981c100.midY == UIView:0x7983e5e0.midY + 384>" 
) 

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7981a220 V:[UILayoutContainerView:0x7981c100]-(0)-| (Names: '|':UIView:0x7983e5e0)> 

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. 
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 
+0

исправлено с помощью splitView.setTranslatesAutoresizingMaskIntoConstraints (false) –

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