5

谁能向我解释您在下面的屏幕截图中看到的边距来自哪里?我希望红色、绿色和蓝色矩形在屏幕布局、横向和纵向中都彼此相邻。相反,我在视图之间看到了莫名其妙的边距。

// Setup Left Bar Button item
UIBlankToolbar* tools = [[[UIBlankToolbar alloc] initWithFrame:CGRectMake(0, 0, 115, 44)] autorelease];
tools.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[tools setBackgroundColor:[UIColor greenColor]];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];

...

// Setup Right Bar Button Item
UIBlankToolbar* tools = [[[UIBlankToolbar alloc] initWithFrame:CGRectMake(0, 0, 100, 44)] autorelease];
[tools setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[tools setBackgroundColor:[UIColor redColor]];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];

...

// Setup Title View
self.navigationItem.titleView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 44)] autorelease];
self.navigationItem.titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.navigationItem.titleView setBackgroundColor:[UIColor blueColor]];

我用这段代码看到的:

在此处输入图像描述 在此处输入图像描述

真正让我感到困惑的是,随着可用空间变小,视图之间的边距变得越来越大?我不明白他们为什么在那里,也不明白为什么他们的行为与我对利润的期望背道而驰。

谢谢!

4

1 回答 1

4

导航栏在其强制执行的项目之间具有最小边距,这就是您无法摆脱边距的原因。

解释您的具体代码也不是很困难:115+100+50 = 265屏幕宽度为 320,因此导航栏有 55 个像素用作边距。左边的项目是左对齐的,右边的项目是右对齐的,中间的项目是居中的。因此,您在肖像中获得的边距非常有意义。

您在横向中看到的内容是由于您的灵活宽度。您不应该在导航栏中的项目上具有灵活的宽度,因此这样做时的行为是未定义的,即错误在于您如何使用导航栏而不是导航栏本身。

发生的事情是首先计算正确项目的新大小。它从 100 增长到100+(480-320) = 260. 然后计算中间项目的大小,看起来它只需要所有可用的大小。当需要计算左侧项目时,它实际上会缩小,因为右侧和中间项目占用了所有空间,因此当导航栏强制设置边距时,像素是从左侧项目中获取的。

实际算法可能有所不同。毕竟它是封闭源代码,我试图解释未定义的行为,但看看产生的利润似乎是正在发生的事情。

无论如何,您的应用程序永远不应该依赖未定义的行为,因为未定义的行为可能会在版本之间发生变化并破坏它。您应该做的是创建自己的自定义视图并将其添加为导航栏的子视图。然后,您将以您想要的方式处理视图中的边距。

yourView = [[YourView alloc] initWithFrame:(UIInterfaceOrientationIsPortrait(interfaceOrientation)) ? CGRectMake(0, 0, 320, 44) : CGRectMake(0, 0, 480, 44)];
yourView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.navigationController.navigationBar addSubview:yourView];
于 2011-05-29T14:55:04.983 回答