2015-06-20 3 views
0

У меня есть программный UIToolBar, который создан и создан в методе viewWillAppear: моего определенного ViewController. У меня есть установка NSLayoutConstraint, чтобы сохранить мою панель инструментов в нижней части экрана, и она подходит для iPhone 4 и 5. Вот мой код:NSLayoutConstraint, вызывающий программную панель инструментов, не отображаться

- (void)viewWillAppear:(BOOL)animated 
{ 
    keyboardSuggestionsOpen = NO; 

    //Create custom UIToolBar 
    commentToolBar = [[UIToolbar alloc] init]; 
    commentToolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44); //108 


    //[self.view removeConstraints:self.view.constraints]; 
    //Remove all contraints on the toolbar 
    for(NSLayoutConstraint *c in self.view.constraints) 
     if(c.firstItem == commentToolBar || c.secondItem == commentToolBar) 
      [self.view removeConstraint:c]; 

    [self.view setTranslatesAutoresizingMaskIntoConstraints:YES]; 
    [self.commentToolBar setTranslatesAutoresizingMaskIntoConstraints:NO]; 


    commentToolBar.backgroundColor = [UIColor blackColor]; 
    commentToolBar.tintColor = [UIColor blackColor]; 
    commentToolBar.barStyle = UIBarStyleBlackOpaque; 

    //self.commentToolBar.translatesAutoresizingMaskIntoConstraints = YES; 
    //self.commentsContainerView.translatesAutoresizingMaskIntoConstraints = YES; 

    [commentTextView setFont:[UIFont systemFontOfSize:22]]; 
    commentTextView.textAlignment = NSTextAlignmentLeft; 
    commentTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 205, 35)]; 
    [commentTextView setBackgroundColor:[UIColor whiteColor]]; 
    [commentTextView.layer setCornerRadius:4.0f]; 

    UIBarButtonItem *textViewItem = [[UIBarButtonItem alloc] initWithCustomView:commentTextView]; 

    commentTextView.delegate = self; 
    [commentTextView setReturnKeyType:UIReturnKeyDone]; 

    commentButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [commentButton setFrame:CGRectMake(0, 0, 75, 35)]; 
    [commentButton.layer setMasksToBounds:YES]; 
    [commentButton.layer setCornerRadius:4.0f]; 
    [commentButton.layer setBorderWidth:0.75f]; 
    [commentButton.layer setBackgroundColor:[[UIColor colorWithHexString:@"669900"]CGColor]]; 
    [commentButton setTitle:@"Comment" forState:UIControlStateNormal]; 
    commentButton.titleLabel.font = [UIFont systemFontOfSize:14.0f]; 
    [commentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    [commentButton addTarget:self action:@selector(commentButtonInvoked:) forControlEvents:UIControlEventTouchUpInside]; 

    commentTextView.textColor = [UIColor lightGrayColor]; 
    commentTextView.text = @"Comment.."; 

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; 

    UIBarButtonItem *commentButtonItem = [[UIBarButtonItem alloc] initWithCustomView:commentButton]; 
    [commentButtonItem setStyle:UIBarButtonItemStylePlain]; 

    [self.commentToolBar setItems:[NSArray arrayWithObjects: textViewItem,flexSpace,commentButtonItem, nil] animated:YES]; 

    [self.view addSubview:commentToolBar]; 


    NSDictionary* views = NSDictionaryOfVariableBindings(commentToolBar); 
    NSString *format = @"V:[commentToolBar(==44)]-|"; 
    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:format 
                  options:0 
                  metrics:nil 
                  views:views]; 

    [self.view layoutSubviews]; 

    [self.view addConstraints:constraints]; 
} 

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

PS - я предоставил фотографию и еще несколько методов, которые могут иметь отношение к погрузке/видимость моего UIToolbar

Это то, что он выглядит как после загрузки:

ответ

1

Проблема в том, что ваши ограничения на панели инструментов недостаточны. Вы обеспечиваете его высоту и вертикальное положение, но вы ничего не сказали о том, где он должен быть горизонтально. Таким образом, это ни к чему не приводит. Недостаточные (неоднозначные) ограничения очень обычно привлекают к себе внимание, когда представление просто не отображается в интерфейсе - и так в вашем случае.

+0

Я на самом деле совершенно не новичок в использовании NSString для создания формата ограничения. Я не уверен, как на самом деле добавить это в мой '@" V: [commentToolBar (== 44)] - | "', также почему мой textView рисуется в нужном месте, когда он кадр рисован, а затем добавлен как subview to toolBar? – Chisx

+0

«Я не уверен, как на самом деле добавить это». Вы добавляете больше ограничений в отдельной строке (или строках) кода. – matt

+0

«Почему мой textView рисуется в нужном месте, когда его кадр рисуется, а затем добавляется как subview в toolBar? Потому что текстовое представление не находится под влиянием автоматического макета. Панель инструментов. Текстовое представление позиционируется по кадру. Панель инструментов помещается ограничениями. У вас есть правый кадр (или, по крайней мере, он выглядит правильно на этом экране). Вы ошиблись. – matt

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