【问题标题】:How to add a UIToolbar programmatically to an iOS app?如何以编程方式将 UIToolbar 添加到 iOS 应用程序?
【发布时间】:2011-12-04 10:46:43
【问题描述】:

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

【问题讨论】:

    标签: ios uitoolbar


    【解决方案1】:

    UIToolbarUIView 的子类,所以对您的问题的简短回答是:就像任何其他视图一样。

    具体来说,这是一个如何以编程方式创建工具栏的示例。这个 sn-p 中的上下文是视图控制器的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 文档。

    【讨论】:

    • 我喜欢把按钮放在工具栏的中心,我该怎么做?
    • @MicRO 现在可能已经弄清楚了,但是:UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    • 尽可能使用视图控制器的navigationController 属性。 stackoverflow.com/a/12313602/242933
    • 最好在 viewDidLayoutSubviews 中执行此操作,因为横向模式下 UIToolbar 的大小不同。
    【解决方案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;
    

    我希望它对你有用。

    【讨论】:

    • 我认为这种方法更好,因为工具栏的高度将来可能会改变。
    • 有什么简单的方法可以让这只小狗动起来吗?我的一个 VC 使用它,但它下面的那个没有。切换不连续。
    • 我认为这是一个更好的答案。
    • 要制作动画,请使用[self.navigationController setToolbarHidden:NO animated:YES] 请注意self.navigationController.toolbar.items = items 起作用。 :-)
    • 我应该将toolbarItems 设置为init 还是viewDidLoad?我们可以在init 中执行此操作,因为我们不需要访问view 即可执行此操作。但是,iOS 真的不应该在viewDidLoad 之后访问toolbarItems。如果是这样的话,那么我宁愿推迟并在viewDidLoad中设置toolbarItems
    【解决方案3】:

    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 专业人士。但是在 viewDidAppear 中添加视图项似乎是错误的。例如,如果您在其顶部呈现一个视图然后关闭,viewDidAppear 会被调用并在其顶部添加另一个 UIToolbar? :)
    • @HelloimDarius 真的!但是,您可以根据您的用例进行定义。
    • @Jack 它不适用于旋转,约束应该在view 而不是guide
    • @GSerjo 约束必须不管safeAreaLayoutGuide,否则toolBar 将与home-indicator 重叠
    • @Jack,正如你在第二张截图中看到的那样,工具栏看起来有点奇怪,这是因为约束
    【解决方案4】:

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

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

    注意:要在 Button 之间留出空间,我们添加如下行

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

    并将间隔添加到

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

    【讨论】:

      【解决方案5】:

      试试这个简单的方法:

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

          斯威夫特 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")
          }
          

          【讨论】:

            猜你喜欢
            • 2011-08-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-25
            • 1970-01-01
            • 1970-01-01
            • 2014-07-16
            • 1970-01-01
            相关资源
            最近更新 更多