7

我有一个分段控制。每当视图完成出现时,我都会创建一个条形按钮项来保存它并将其设置为工具栏项。我遇到的问题是分段控件不会填充工具栏中的空间,即使它设置为具有空间填充行为。

如何在 iOS 应用程序的工具栏中有一个填充空间的分段控件?

4

2 回答 2

1

听起来您正试图从 UIToolbar 中获取非标准工具栏行为。为什么不直接放一个 UIView 并以正常方式用 UISegmentedControl 填充它?您需要 UIToolbar 的某些特定功能吗?

于 2012-05-04T01:51:29.590 回答
0

UIView 通常没有“空间填充行为”。他们得到分配给他们的大小。你所能做的就是:

  1. 设置他们的自动调整掩码以控制如果他们的父视图改变其大小,他们如何调整大小
  2. 设置他们的 UIViewContentMode 来控制他们如何调整他们的内容(例如对 UIImageViews 很重要)

在您的情况下,您可以执行以下操作来获取包含与工具栏一样宽的 UISegmentedControl 的 UIToolbar:

(void)viewDidLoad
{
    [super viewDidLoad];

    //  Create the toolbar; place it at the bottom of the view.
    UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-44, self.view.bounds.size.width, 44)];
    myToolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:myToolbar];

    //  Create the UISegmentedControl with two segments and "Bar" style. Set frame size to that of the toolbar minus 6pt margin on both sides, since 6pt is the padding that is enforced anyway by the UIToolbar.
    UISegmentedControl *mySegmentedControl = [[UISegmentedControl alloc] initWithFrame:CGRectInset(myToolbar.frame, 6, 6)];
    //  Set autoresizing of the UISegmentedControl to stretch horizontally.
    mySegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    [mySegmentedControl insertSegmentWithTitle:@"First" atIndex:0 animated:NO];
    [mySegmentedControl insertSegmentWithTitle:@"Second" atIndex:1 animated:NO];
    mySegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 

    //  Create UIBarButtonItem with the UISegmentedControl as custom view, and add it to the toolbar's items
    UIBarButtonItem *myBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mySegmentedControl];
    myToolbar.items = [NSArray arrayWithObject:myBarButtonItem];
}
于 2012-05-09T11:38:19.747 回答