我正在创建一个只放在UIToolbar上的UILabel。标签内容是动态的,可以更改,我想把它集中在一个UIToolbar上。
有谁知道UIToolbar的左右边的确切的边距大小吗?
我正在创建一个[UIBarButtonItem alloc initWithCustomView: myLabelContainer ],并试图确保myLabelContainer占用整个工具栏空间,减去强制页边距。
现在,我已经猜到,边距大约是12 px,所以一个帧宽为296的UIView应该填充整个UIToolbar?
这些信息在任何地方都能得到吗?
发布于 2011-04-18 19:57:53
我不认为这些信息是可以得到的。但是通过一些测试应该很容易得到。
如果您需要的只是整个工具栏上的一个UILabel,我建议将它添加到UIToolbar中,这是一个UIView子类。在你的情况下,你不需要所有的UIBarButtonItem特性.只是我想的背景。
然后设置UILabel.frame (带您想要的边距)+ addSubview: + UITextAlignmentCenter应该可以完成这个工作!如果你有管理设备方向的话,也许还有一个autoresizingMask和UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight .
编辑1:
由于对这一建议有一些疑问,我做了一个简短的试验:
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 44)] autorelease];
label.text = @"Hello world";
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor blackColor];
label.backgroundColor = RGBACOLOR(255, 0, 0, .3f);
[self.toolbar addSubview:label];结果如下:

编辑2:
现在我已经启动了Xcode并编写了一些代码,这很容易理解您的主要问题。修改一下以前的代码:
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease];
... same
[self.toolbar setItems:
[NSArray arrayWithObject:
[[[UIBarButtonItem alloc] initWithCustomView:label] autorelease]]];因此:

因此,正如您所猜测的,左边距为12 in,但自定义视图看起来不像是要调整大小以适应,因此,在这种情况下没有右边距.除非你相应地调整你的观点。
编辑3:
除非您的UILabel需要背景,否则我可能会这样做(毕竟,这就是UIBarButtonSystemItemFlexibleSpace的目的.):
UILabel *label = [[[UILabel alloc] init] autorelease];
label.text = @"Hello world";
... same
[label sizeToFit];
[self.toolbar setItems:
[NSArray arrayWithObjects:
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil] autorelease],
[[[UIBarButtonItem alloc] initWithCustomView:label] autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil] autorelease],
nil]];结果:

编辑4:
另外,在对UIToolbar做了更多的工作之后,12px是在按钮之前添加的默认空间。我刚刚发现了一个有趣的例子,间隔器使用的是负值!。也就是说,如果您想在两个按钮之间有一个2px空间,只需添加一个-10 2pxUIBarButtonSystemItemFixedSpace.手巧!
发布于 2016-04-22 15:52:12
似乎没有存储这个边距的地方,但是这里有一种在Xamarin中计算这一点的方法。首先向ViewController中的工具栏添加一个按钮:
UIButton button = new UIButton();
button.Tag = 999;
ToolbarItems = new[] { FilterButton };然后使用此代码读取(使用断点)任何特定方向和设备的填充值。(我已经为该方向添加了一个变量,因为这将告诉您,如果您在旋转事件中调用此代码,该应用程序当前的方向是什么。)
if (NavigationController != null)
{
UIButton firstButton = NavigationController.Toolbar.Subviews
.FirstOrDefault(x => x.GetType() == typeof(UIButton) && x.Tag == 999);
if (firstButton != null)
{
var orientation = UIApplication.SharedApplication.StatusBarOrientation;
var padding = firstButton.Frame.X;
}
}作为记录,对于iOS9,iPhones上的纵向值为16,景观值为20,iPads上的值为20。
https://stackoverflow.com/questions/5708058
复制相似问题