将 UILabel 添加到 UIToolbar

发布于 2024-07-10 04:03:15 字数 826 浏览 12 评论 0原文

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

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

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

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

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

发布评论

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

评论(10

伊面 2024-07-17 04:03:16

我使用这个技巧的目的之一是在 UIToolBar 之上实例化一个 UIActivityIndi​​catorView,否则这是不可能的。 例如,这里我有一个带有 2 个 UIBarButtonItem 的 UIToolBar、一个 FlexibleSpaceBarButtonItem 和另一个 UIBarButtonItem。 我想在灵活空间和最终(右侧)按钮之间的 UIToolBar 中插入 UIActivityIndi​​catorView 。 因此,在我的 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];}

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

- (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];}
孤者何惧 2024-07-17 04:03:16

详细信息

  • Xcode 10.2.1 (10E1001)、Swift 5

完整示例

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) }
}

结果

在此处输入图像描述

Details

  • 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

剪不断理还乱 2024-07-17 04:03:16

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

  1. 添加 webview 来代替。
  2. 取消选中不透明
  3. 确保背景颜色清晰
  4. IBOutlet 连接所有内容
  5. 使用下面的 html 获得透明背景,以便工具栏通过

代码发光:

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

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

  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 html to have a transparent background so the toolbar shines through

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];
遗忘曾经 2024-07-17 04:03:16

如果您想在工具栏视图上添加视图,您可以尝试以下操作:

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

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

[self.navigationController.tabBarController.view addSubview:yourView];
私藏温柔 2024-07-17 04:03:16

试试这个:

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

注意:self.barItem 是一个从对象库添加的 UIBarButtonItem,并放置在两个灵活空间之间。

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

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.barItem is a UIBarButtonItem added from the object library and placed between two flexible spaces.

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,

究竟谁懂我的在乎 2024-07-17 04:03:16

可以使用禁用的 BarButtonItem

let resultsLabel = UIBarButtonItem(title: "number of results", style: .plain, target: self, action: nil)
resultsLabel.isEnabled = false

could use a disabled BarButtonItem

let resultsLabel = UIBarButtonItem(title: "number of results", style: .plain, target: self, action: nil)
resultsLabel.isEnabled = false
染火枫林 2024-07-17 04:03:16

Swift 中的解决方案

实现此目的的一种方法是创建一个 UILabel,然后将其作为自定义视图添加到您可以使用的 UIBarButtonItem然后添加到工具栏。
例如:

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setToolbarHidden(false, animated: false)
        
        let textLabel = UILabel()
        textLabel.font = UIFont.systemFont(ofSize: 17)
        textLabel.text = "Text Label" // Change this to be any string you want
        let textButton = UIBarButtonItem(customView: textLabel)
        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        setToolbarItems([spacer, textButton, spacer], animated: false)
    }
    
}

注意:flexibleSpace 将标签放置在工具栏的中心

下面是其外观的屏幕截图:
示例屏幕截图

注意:如果没有选项卡栏,工具栏将占据屏幕底部。

A solution to this in Swift

One way you could do this is by creating a UILabel and then adding it as custom view to a UIBarButtonItem which you then add to the toolbar.
For example:

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setToolbarHidden(false, animated: false)
        
        let textLabel = UILabel()
        textLabel.font = UIFont.systemFont(ofSize: 17)
        textLabel.text = "Text Label" // Change this to be any string you want
        let textButton = UIBarButtonItem(customView: textLabel)
        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        setToolbarItems([spacer, textButton, spacer], animated: false)
    }
    
}

NOTE: The flexibleSpace's position the label in the centre of the tool bar

Here's a screenshot of what this would look like:
Example Screenshot

NOTE: Without a tab bar the toolbar would take up the bottom of the screen.

几度春秋 2024-07-17 04:03:15

看一下

[[UIBarButtonItem alloc] initWithCustomView:yourCustomView];

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

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

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];
一紙繁鸢 2024-07-17 04:03:15

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

要将 UILabel 添加到 UIToolBar,您需要通过拖动将通用 UIView 对象添加到 IB 中的 UIToolBar UIToolBar 上的新 UIView 对象。 IB 将自动创建一个 UIBarButtonItem,并将使用您的自定义 UIView 进行初始化。 接下来将 UILabel 添加到 UIView 并以图形方式编辑 UILabel 以匹配您喜欢的样式。 然后,您可以根据需要直观地设置固定和/或可变垫片,以适当定位您的 UILabel

您还必须将 UILabelUIView 的背景设置为 clearColor 以使 UIToolBar 显示出来正确位于 UILabel 下。

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

To add a UILabel to a UIToolBar you need to add a generic UIView object to your UIToolBar in IB by dragging a new UIView object over your UIToolBar. IB will automatically create a UIBarButtonItem that will be initialized with your custom UIView. Next add a UILabel to the UIView and edit the UILabel graphically to match your preferred style. You can then visually set up your fixed and/or variable spacers as desired to position your UILabel appropriately.

You must also set the background of both the UILabel and the UIView to clearColor to get the UIToolBar to show through correctly under the UILabel.

一场春暖 2024-07-17 04:03:15

我发现answerBot的答案非常有用,但我认为我在界面生成器中找到了一种更简单的方法:

  • 创建一个 UIBarButtonItem 并将其添加到界面中的工具栏
    Builder

在此处输入图像描述

  • 取消选中此 BarButtonItem 的“启用”

在此处输入图像描述

  • 将此 BarButtonItem 插入类中的属性(位于
    Swift,但在 Obj-C 中非常相似):

    @IBOutlet 私有弱变量lastUpdateButton:UIBarButtonItem!   // 自定义View为lastUpdateLabel的虚拟barButtonItem 
      
  • 为标签本身添加另一个属性:

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

    // 包含上次更新日期的虚拟按钮 
      最后更新标签.sizeToFit() 
      lastUpdateLabel.backgroundColor = UIColor.clearColor() 
      最后更新标签.textAlignment = .Center 
      最后更新按钮.customView = 最后更新标签 
      
  • 要更新 UILabel 文本:

    lastUpdateLabel.text = "更新时间:2014 年 9 月 12 日,2:53" 
      最后更新标签.sizeToFit()  
      

结果:

在此处输入图像描述

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

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

  • create a UIBarButtonItem and add it to your Toolbar in Interface
    Builder

enter image description here

  • Uncheck "enabled" for this 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 UILabel text:

    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

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