Подтвердить что ты не робот

Как добавить UIToolbar программно в приложение iOS?

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

4b9b3361

Ответ 1

UIToolbar является подклассом UIView, поэтому короткий ответ на ваш вопрос: как и любой другой вид.

В частности, это пример того, как программно создавать панель инструментов. Контекст в этом фрагменте viewDidLoad контроллера вида.

UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:[[[UIBarButtonItem alloc] initWith....] autorelease]];
[toolbar setItems:items animated:NO];
[items release];
[self.view addSubview:toolbar];
[toolbar release];

Смотрите UIToolbar и UIBarButtonItem документация для деталей.

Ответ 2

Если вы используете UINavigationController, тогда панель инструментов поставляется с ней по умолчанию.

Вы можете добавить его, используя следующую строку кода:

self.navigationController.toolbarHidden = NO;

И чтобы добавить кнопку на панель инструментов, вы можете использовать следующий код:

UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];

flexibleItem используется для поддержания правильного расстояния между двумя кнопками, которые мы создали выше.

Теперь вы можете добавить эти три элемента, чтобы сделать их видимыми на вашем экране.

NSArray *items = [NSArray arrayWithObjects:item1, flexibleItem, item2, nil];   
self.toolbarItems = items;

Я надеюсь, что это сработает для вас.

Ответ 3

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

-(void)showToolBar
{
    CGRect frame, remain;
    CGRectDivide(self.view.bounds, &frame, &remain, 44, CGRectMaxYEdge);
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:frame];
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"Send" style:UIBarButtonItemStyleDone target:self action:nil];
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *button2=[[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:self action:nil];
    [toolbar setItems:[[NSArray alloc] initWithObjects:button1,spacer,button2,nil]];
    [toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    [self.view addSubview:toolbar];
}

Примечание. Чтобы задать пробел между кнопками, добавьте строку ниже

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

и добавьте spacer к

[toolbar setItems:[[NSArray alloc] initWithObjects:button1,spacer,button2,nil]];

Ответ 4

iOS 11+ SWIFT 4 + Xcode 9 + Ограничения

Работает как для пейзажа + Портрет введите описание изображения здесь

Портрет

    override func viewDidLoad() {
        super.viewDidLoad()
        print(UIApplication.shared.statusBarFrame.height)//44 for iPhone x, 20 for other iPhones
        navigationController?.navigationBar.barTintColor = .red


        let toolBar = UIToolbar()
        var items = [UIBarButtonItem]()
        items.append(
            UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil)
        )
        items.append(
            UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(tapsOnAdd))
        )
        toolBar.setItems(items, animated: true)
        toolBar.tintColor = .red
        view.addSubview(toolBar)

        toolBar.translatesAutoresizingMaskIntoConstraints = false


        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            toolBar.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            toolBar.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            toolBar.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
            toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true

        }
        else {
            NSLayoutConstraint(item: toolBar, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: toolBar, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: toolBar, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true

            toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
        }

    }

Ответ 5

Вот как вы реализуете UIToolbar в своем приложении.

// declare frame of uitoolbar 
UIToolBar *lotoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 170, 320, 30)];
[lotoolbar setTintColor:[UIColor blackColor]];

UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"DATE" style:UIBarButtonItemStyleDone target:self action:@selector(dateToolbardoneButtonAction)];

UIBarButtonItem *button2=[[UIBarButtonItem alloc]initWithTitle:@"TIME" style:UIBarButtonItemStyleDone target:self action:@selector(timeToolbarbuttonAction)];

[lotoolbar setItems:[[NSArray alloc] initWithObjects:button1, nil];
[lotoolbar setItems:[[NSArray alloc] initWithObjects:button2, nil];
[mainUIview addSubview:lotoolbar];

Вам также необходимо реализовать следующие методы делегата:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
}
- (void)textViewDidChange:(UITextView *)textView{
    NSLog(@"textViewDidChange:");
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"textViewDidChangeSelection:");
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [lotextview setText:@""];
    NSLog(@"textViewShouldBeginEditing:");
    return YES;
}

Ответ 6

Попробуйте этот простой метод:

    UIToolbar *toolbar = [[UIToolbar alloc] init];
    toolbar.frame = CGRectMake(0, 0, 300, 44);
    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"Send" style:UIBarButtonItemStyleDone target:self action:@selector(sendAction)];

    UIBarButtonItem *button2=[[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:self action:@selector(cancelAction)];

    [toolbar setItems:[[NSArray alloc] initWithObjects:button1,button2, nil]];
    [self.view addSubview:toolbar];