如何以编程方式将 UIToolbar 添加到 iOS 应用程序?

发布于 2024-12-09 01:28:42 字数 61 浏览 0 评论 0 原文

似乎找不到按照问题标题描述的教程。我想了解 UIToolbar 需要在哪里声明以及如何将其放到我的视图层上。

Can't seem to find a tutorial which does as the question title describes. I'd like to understand just where the UIToolbar needs to be declared and how to get it onto my view layer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

颜漓半夏 2024-12-16 01:28:43

如果您使用的是 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;

我希望它对你有用。

If you're using UINavigationController then the toolbar comes with it by default.

You can add it using following line of code:

self.navigationController.toolbarHidden = NO;

And to add button to your Toolbar you can use following code:

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 is used to maintain proper distance between the two buttons that we have created above.

Now you can add these three items in order to make them visible on your view.

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

I hope it works for you.

赤濁 2024-12-16 01:28:43

UIToolbarUIView 的子类,因此您的问题的简短答案是:就像任何其他视图一样。

具体来说,这是如何以编程方式创建工具栏的示例。此代码片段中的上下文是视图控制器的 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];

请参阅 UIToolbarUIBarButtonItem< /a> 文档以获取详细信息。

UIToolbar is a subclass of UIView, so the short answer to your question is: just like any other view.

Specifically, this is an example of how to programmatically create a toolbar. The context in this snippet is viewDidLoad of a view controller.

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];

See UIToolbar and UIBarButtonItem documentation for details.

心如荒岛 2024-12-16 01:28:43

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
        }

    }

iOS 11+ SWIFT 4 + Xcode 9 + Constraints

Works for both landscape + Portrait
enter image description here

Portrait

    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
        }

    }
孤芳又自赏 2024-12-16 01:28:43

要在底部显示工具栏,左侧的两个按钮和右侧的另一个按钮之间有空间

-(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];

< strong>并添加间隔符

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

To show the Toolbar at the bottom with space between two button on at Left Side , and another at Right side

-(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];
}

Note: To Give space between to Button we add line as below

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

and add spacer to the

[toolbar setItems:[[NSArray alloc] initWithObjects:button1,spacer,button2,nil]];
眼睛会笑 2024-12-16 01:28:43

尝试这个简单的方法:

    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];

Try this simple Method:

    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];
童话里做英雄 2024-12-16 01:28:43

这就是您在应用中实现 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;
}

This is how you implement a UIToolbar in your app.

// 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];

You should also have to implement the following delegate methods:

- (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;
}
瞳孔里扚悲伤 2024-12-16 01:28:43

Swift 5:

结果:
输入图片此处描述

代码:

override func viewDidLoad() {
    
    super.viewDidLoad()
    
    self.view.backgroundColor = .systemBackground
    
    self.navigationController?.isToolbarHidden = false
    
    let toolBarItems = ["Tab1","Tab2"]
    segmentedControl = UISegmentedControl(items: toolBarItems)
    segmentedControl.selectedSegmentIndex = 0

    let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
    let cameraBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil)
    let segmentedControlBarButtonItem = UIBarButtonItem(customView: segmentedControl)
    let addBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction))
    self.toolbarItems = [cameraBarButtonItem, space, segmentedControlBarButtonItem, space, addBarButtonItem]
    
}

@objc func addAction() {
    print("Add")
}

Swift 5:

Result:
enter image description here

Code:

override func viewDidLoad() {
    
    super.viewDidLoad()
    
    self.view.backgroundColor = .systemBackground
    
    self.navigationController?.isToolbarHidden = false
    
    let toolBarItems = ["Tab1","Tab2"]
    segmentedControl = UISegmentedControl(items: toolBarItems)
    segmentedControl.selectedSegmentIndex = 0

    let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
    let cameraBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: nil)
    let segmentedControlBarButtonItem = UIBarButtonItem(customView: segmentedControl)
    let addBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction))
    self.toolbarItems = [cameraBarButtonItem, space, segmentedControlBarButtonItem, space, addBarButtonItem]
    
}

@objc func addAction() {
    print("Add")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文