【问题标题】:Adding a UILabel to a UIToolbar将 UILabel 添加到 UIToolbar
【发布时间】:2010-09-24 21:49:17
【问题描述】:

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

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

【问题讨论】:

    标签: ios iphone uibarbuttonitem


    【解决方案1】:

    看看这个

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

    【讨论】:

    • 请注意,如果您选择走这条路线,则必须适当地设置标签的样式(label.backgroundColor = [UIColor clearColor] 等)。您还可以初始化一个 UIBarButtonItem 样式为 Plain ,这会给您类似的外观
    • 我知道这是一篇很老的帖子,但我对这个答案有疑问。完成后,以后有什么方法可以访问titleLabel来更改它,还是因为所有内容都已发布,所以这是不可能的?
    • Ryan,UILabel 可能还存在——它是 self.titleLabel。此示例需要为 UILabel *titleLabel 声明和合成一个属性,但未显示该代码。如果您有权访问运行此代码的对象(可能是 UIViewController),则可以访问其 titleLabel。例如,您可以在视图控制器上添加一个方法,传入您想要的新标题,然后调用 [self.titleLabel setText:newTitle]。
    • 您不想在标题按钮栏项目之后添加第二个空格吗?
    【解决方案2】:

    对于那些使用 Interface Builder 来布局您的 UIToolBar 的人,也可以单独使用 Interface Builder 来做到这一点。

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

    您还必须将UILabelUIView 的背景设置为clearColor,以使UIToolBarUILabel 下正确显示。

    【讨论】:

    • 不错的技巧,不知道你可以在 Interface Builder 中做到这一点。非常感谢。
    • 有没有办法使用该方法添加带有自定义图像的 UIButton?我可以添加一个 UIButton,但图像不显示。
    • 我似乎无法让它工作。当我将 UIView 拖到工具栏上时,它最终被放置在视图控制器内,而不是工具栏上。另外,我们是在导航控制器中还是在视图控制器中执行此操作?
    • 这似乎不起作用。如果它在很久以前就有效,那么在 XCode 6 中就不再有效了……
    • 您应该更新您的答案以指出这仅适用于手动添加到视图控制器的工具栏;它不适用于为您添加的工具栏。
    【解决方案3】:

    我发现 answerBot 的回答非常有用,但我认为我在 Interface Builder 中找到了更简单的方法:

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

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

    • 将此 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() 
      

    结果:

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

    【讨论】:

    • 我创建了一个和你一样的 UIBarButtonItem,让它保持启用状态,并使用以下代码叠加一个标签:UILabel* label = [[UILabel alloc] init]; label.text = @"Hello"; label.font = [UIFont systemFontOfSize:16]; [label sizeToFit]; self.barItem.customView = label;
    【解决方案4】:

    我使用这个技巧的一件事是在UIToolBar 之上实例化UIActivityIndicatorView,否则这是不可能的。例如这里我有一个UIToolBar 和两个UIBarButtonItem,一个FlexibleSpaceBarButtonItem,然后是另一个UIBarButtonItem。我想在灵活空间和最终(右手)按钮之间的UIToolBar 中插入一个UIActivityIndicatorView。因此,在我的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];}
    

    【讨论】:

    • 此代码泄漏了为 UIBarButtonItem 分配的内存以及自定义活动指示器视图。 (它也会泄漏活动指示器的内存,但我认为它是在代码片段末尾下方释放的。
    【解决方案5】:

    详情

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

    结果

    【讨论】:

    • 我喜欢这个,但是如果我有 TableView 那么它会随着这个栏滚动。我该如何解决?
    • 您好 Maxim,我无法理解您的问题。请描述你想要得到的结果。
    • 好的,我正在使用 UITableViewController,如果我设置 view.addSubview(toolBar!) 并滚动我的 tableview 栏将随着 tableView 滚动,我希望它有一个固定的底部位置
    • 我认为,您应该使用 UIViewController 和 UITableView(而不是 UITableViewController)作为子视图。
    • 好的,斯帕西博。我会试试的
    【解决方案6】:

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

    1. 改为添加 web 视图。
    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];
    

    【讨论】:

      【解决方案7】:

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

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

      【讨论】:

        【解决方案8】:

        试试这个:

        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(宽度)的参数,使其填满整个工具栏,并在代码中自行设置对齐方式为中间和字体,

        【讨论】:

          【解决方案9】:

          可以使用禁用的 BarButtonItem

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

          【讨论】:

            【解决方案10】:

            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 将标签定位在工具栏的中心

            这是一个截图:

            注意:如果没有标签栏,工具栏将占据屏幕底部。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-10-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多