ios 将 UILabel 添加到 UIToolbar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/333441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:25:21  来源:igfitidea点击:

Adding a UILabel to a UIToolbar

iosiphoneuibarbuttonitem

提问by Matt R

I'm trying to add a label to my toolbar. Button works great, however when I add the label object, it crashes. Any ideas?

我正在尝试向我的工具栏添加标签。按钮效果很好,但是当我添加标签对象时,它崩溃了。有任何想法吗?

UIBarButtonItem *setDateRangeButton = [[UIBarButtonItem alloc] initWithTitle:@"Set date range"
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:@selector(setDateRangeClicked:)];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
label.text = @"test";

[toolbar setItems:[NSArray arrayWithObjects:setDateRangeButton,label, nil]];

// Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];

// Reload the table view
[self.tableView reloadData];

回答by adam

Have a look into this

看看这个

[[UIBarButtonItem alloc] initWithCustomView:yourCustomView];

Essentially every item must be a "button" but they can be instantiated with any view you require. Here is some example code. Note, since other buttons are typically on the toolbar, spacers are placed on each side of the title button so it stays centered.

基本上每个项目都必须是一个“按钮”,但它们可以使用您需要的任何视图进行实例化。这是一些示例代码。请注意,由于其他按钮通常位于工具栏上,因此在标题按钮的每一侧放置了间隔符,以便它保持居中。

NSMutableArray *items = [[self.toolbar items] mutableCopy];

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:spacer];
[spacer release];

self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width, 21.0f)];
[self.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
[self.titleLabel setBackgroundColor:[UIColor clearColor]];
[self.titleLabel setTextColor:[UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]];
[self.titleLabel setText:@"Title"];
[self.titleLabel setTextAlignment:NSTextAlignmentCenter];

UIBarButtonItem *spacer2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:spacer2];
[spacer2 release];

UIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:self.titleLabel];
[items addObject:title];
[title release];

[self.toolbar setItems:items animated:YES];
[items release];

回答by Matt R

For those using Interface Builder to layout your UIToolBar, it is also possible to do this using Interface Builder alone.

对于那些使用 Interface Builder 来布局你的 . 的人UIToolBar,也可以单独使用 Interface Builder 来完成。

To add a UILabelto a UIToolBaryou need to add a generic UIViewobject to your UIToolBarin IB by dragging a new UIViewobject over your UIToolBar. IBwill automatically create a UIBarButtonItemthat will be initialized with your custom UIView. Next add a UILabelto the UIViewand edit the UILabelgraphically to match your preferred style. You can then visually set up your fixed and/or variable spacers as desired to position your UILabelappropriately.

要添加UILabelUIToolBar您需要一个通用的加入UIView对象添加到您UIToolBar通过拖动一个新的IBUIView在你的对象UIToolBarIB将自动创建一个UIBarButtonItem将使用您的自定义UIView. 接下来添加UILabelUIView和编辑UILabel图形,以配合您的首选风格。然后,您可以根据需要直观地设置固定和/或可变垫片,以UILabel适当放置。

You must also set the background of both the UILabeland the UIViewto clearColorto get the UIToolBarto show through correctly under the UILabel.

您还必须设置两个背景UILabelUIViewclearColor获得UIToolBar下正确显示通过UILabel

回答by Frédéric Adda

I found answerBot's answer very useful, but I think I found an even easier way, in Interface Builder:

我发现 answerBot 的答案非常有用,但我想我在 Interface Builder 中找到了一种更简单的方法:

  • create a UIBarButtonItem and add it to your Toolbar in Interface Builder
  • 创建一个 UIBarButtonItem 并将其添加到界面生成器中的工具栏

enter image description here

在此处输入图片说明

  • Uncheck "enabled" for this BarButtonItem
  • 取消选中此 BarButtonItem 的“启用”

enter image description here

在此处输入图片说明

  • plug this BarButtonItem to a property in your class (this is in Swift, but would be very similar in Obj-C):

    @IBOutlet private weak var lastUpdateButton: UIBarButtonItem! // Dummy barButtonItem whose customView is lastUpdateLabel
    
  • add another property for the Label itself:

    private var lastUpdateLabel = UILabel(frame: CGRectZero)
    
  • in viewDidLoad, add the following code to set the properties of your label, and add it as the customView of your BarButtonItem

    // Dummy button containing the date of last update
    lastUpdateLabel.sizeToFit()
    lastUpdateLabel.backgroundColor = UIColor.clearColor()
    lastUpdateLabel.textAlignment = .Center
    lastUpdateButton.customView = lastUpdateLabel
    
  • To update the UILabeltext:

    lastUpdateLabel.text = "Updated: 9/12/14, 2:53"
    lastUpdateLabel.sizeToFit() 
    
  • 将此 BarButtonItem 插入类中的属性(这是在 Swift 中,但在 Obj-C 中非常相似):

    @IBOutlet private weak var lastUpdateButton: UIBarButtonItem! // Dummy barButtonItem whose customView is lastUpdateLabel
    
  • 为标签本身添加另一个属性:

    private var lastUpdateLabel = UILabel(frame: CGRectZero)
    
  • 在viewDidLoad中,添加如下代码来设置你的标签的属性,并将其添加为你的BarButtonItem的customView

    // Dummy button containing the date of last update
    lastUpdateLabel.sizeToFit()
    lastUpdateLabel.backgroundColor = UIColor.clearColor()
    lastUpdateLabel.textAlignment = .Center
    lastUpdateButton.customView = lastUpdateLabel
    
  • 要更新UILabel文本:

    lastUpdateLabel.text = "Updated: 9/12/14, 2:53"
    lastUpdateLabel.sizeToFit() 
    

Result :

结果 :

enter image description here

在此处输入图片说明

You have to call lastUpdateLabel.sizetoFit()each time you update the label text

lastUpdateLabel.sizetoFit()每次更新标签文本时都必须调用

回答by Alasdair Allan

One of the things I'm using this trick for is to instantiate a UIActivityIndicatorViewon top of the UIToolBar, something that otherwise wouldn't be possible. For instance here I have a UIToolBarwith 2 UIBarButtonItem, a FlexibleSpaceBarButtonItem, and then another UIBarButtonItem. I want to insert a UIActivityIndicatorViewinto the UIToolBarbetween the flexible space and the final (right-hand) button. So in my RootViewControllerI do the following,

我使用这个技巧的一件事是UIActivityIndicatorView在 之上实例化 a UIToolBar,否则这是不可能的。例如这里我有一个UIToolBar2 UIBarButtonItem, a FlexibleSpaceBarButtonItem,然后另一个UIBarButtonItem。我想插入UIActivityIndicatorViewUIToolBar灵活空间和最终(右手)按钮之间。所以在我的RootViewController我做以下,

- (void)viewDidLoad {
[super viewDidLoad];// Add an invisible UIActivityViewIndicator to the toolbar
UIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:767];
NSArray *items = [toolbar items];

activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];    

NSArray *newItems = [NSArray arrayWithObjects:[items objectAtIndex:0],[items objectAtIndex:1],[items objectAtIndex:2],
                     [[UIBarButtonItem alloc] initWithCustomView:activityIndicator], [items objectAtIndex:3],nil];
[toolbar setItems:newItems];}

回答by Vasily Bodnarchuk

Details

细节

  • Xcode 10.2.1 (10E1001), Swift 5
  • Xcode 10.2.1 (10E1001),Swift 5

Full sample

完整样品

import UIKit

class ViewController: UIViewController {

    private weak var toolBar: UIToolbar?

    override func viewDidLoad() {
        super.viewDidLoad()

        var bounds =  UIScreen.main.bounds
        let bottomBarWithHeight = CGFloat(44)
        bounds.origin.y = bounds.height - bottomBarWithHeight
        bounds.size.height = bottomBarWithHeight
        let toolBar = UIToolbar(frame: bounds)
        view.addSubview(toolBar)

        var buttons = [UIBarButtonItem]()
        buttons.append(UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.action)))
        buttons.append(UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(ViewController.action)))
        buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        buttons.append(ToolBarTitleItem(text: "\(NSDate())", font: .systemFont(ofSize: 12), color: .lightGray))
        buttons.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        buttons.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action:  #selector(ViewController.action)))
        toolBar.items = buttons

        self.toolBar = toolBar
    }
    @objc func action() { print("action") }
}

class ToolBarTitleItem: UIBarButtonItem {

    init(text: String, font: UIFont, color: UIColor) {
        let label =  UILabel(frame: UIScreen.main.bounds)
        label.text = text
        label.sizeToFit()
        label.font = font
        label.textColor = color
        label.textAlignment = .center
        super.init()
        customView = label
    }
    required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
}

Result

结果

enter image description here

在此处输入图片说明

回答by Todd Horst

Similar to Matt R I used interface builder. But I wanted to have 1 UIWebViewinside instead so that i can have some text bolded and other text not (like the mail app). So

类似于 Matt RI 使用的界面构建器。但是我想在UIWebView里面有 1 ,这样我就可以有一些粗体文本,而其他文本则不是(如邮件应用程序)。所以

  1. Add the webview instead.
  2. Uncheck opaque
  3. Make sure background is clear color
  4. Hook everything up with IBOutlet
  5. Use the below htmlto have a transparent background so the toolbar shines through
  1. 改为添加 webview。
  2. 取消选中不透明
  3. 确保背景颜色清晰
  4. 把一切都联系起来 IBOutlet
  5. 使用下面html的有一个透明的背景,使工具栏闪耀

Code:

代码:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *html = [NSString stringWithFormat:@"<html><head><style>body{font-size:11px;text-align:center;background-color:transparent;color:#fff;font-family:helvetica;vertical-align:middle;</style> </head><body><b>Updated</b> 10/11/12 <b>11:09</b> AM</body></html>"];
[myWebView loadHTMLString:html baseURL:baseURL];

回答by user1938695

Try this:

尝试这个:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(140 , 0, 50, 250)];
[label setBackgroundColor:[UIColor clearColor]];
label.text = @"TEXT";
UIView *view = (UIView *) label;
[self.barItem setCustomView:view];

Note: self.barItemis a UIBarButtonItemadded from the object library and placed between two flexible spaces.

注意:self.barItemUIBarButtonItem从对象库中添加的并放置在两个灵活空间之间。

another way is to remove the [self.barItem setCustom:view]line and change the parameters of the label(width) so that it fills the entire toolbar and set the alignment to middle and the font by yourself in code,

另一种方法是删除该[self.barItem setCustom:view]行并更改label(宽度)的参数,使其填满整个工具栏,并在代码中自行设置对齐居中和字体,

回答by Alessandro Ornano

If you want to adding a view up the toolbar view you can try this:

如果你想在工具栏视图上添加一个视图,你可以试试这个:

[self.navigationController.tabBarController.view addSubview:yourView];