如何将 UILabel 添加到 UIToolbar?

Posted

技术标签:

【中文标题】如何将 UILabel 添加到 UIToolbar?【英文标题】:How to add a UILabel to UIToolbar? 【发布时间】:2015-05-12 01:05:07 【问题描述】:

我一直在尝试通过 1) IB UIToolbarUILabel 来复制 Snapchat 在“发送至...”页面底部的蓝色弹出矩形提示,以及 2)以编程方式通过UIToolbar(frame: CGRectMake(x,y,width,height))。在界面生成器中,我无法在工具栏上拖动标签,而且我一直在为编程路线而苦苦挣扎。

在 Swift 中复制该工具栏格式的最佳方法是什么?我的视图控制器将与 Snapchat 的非常相似。单击某人的姓名,工具栏会从底部以动画形式出现,收件人的数组会显示在工具栏上。

我会发布 Snapchat 示例的图片,但我是 S.O 的新手,还没有代表。 :/ 提前致谢!

编辑:这是我所指内容的链接。最底部的蓝色发送提示。它仅在选择 1 个或多个用户时出现。

【问题讨论】:

分享你预期的输出截图。 谢谢@sasquatch。我什至没有足够的声望来发布截图。 如果我的回答对您有帮助,请将其标记为已接受。 我使用了一种更简单的方法。我在 Swift 中要求它。还是谢谢。 感谢您的回复,但我想帮助您。如果你有更好的方法没问题。 【参考方案1】:

试试这个在工具栏上显示标签。

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

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


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


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

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

使用它...

UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:toolbar];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
label.backgroundColor = [UIColor clearColor];

UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:label];
toolbar.items = [NSArray arrayWithObject:item];

label.text = @"Hello World";

【讨论】:

以上是关于如何将 UILabel 添加到 UIToolbar?的主要内容,如果未能解决你的问题,请参考以下文章

在 UIToolbar 中移动 UILabel 的文本

以编程方式将 UILabel 添加到工具栏

如何将 uitoolbar 添加到 uitableviewcontroller?

如何将 UIToolbar 添加到 UIViewController?

如何以编程方式将 UIButton 添加到 UIToolBar?

如何将附加的阴影添加到 uinavigationbar 和 uitoolbar