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

时间:2012-05-02 01:27:20

标签: ios uitoolbar uisegmentedcontrol

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

如何在iOS应用的工具栏中使用空间填充的分段控件?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

一般来说,UIViews没有“空间填充行为”。他们得到他们分配的大小。你所能做的就是:

  1. 设置自动调整遮罩以控制它们的调整大小 父视图更改其大小
  2. 设置他们的UIViewContentMode来控制他们调整内容的方式 (例如,对UIImageViews很重要)
  3. 在您的情况下,您可以执行以下操作以获取包含与工具栏一样宽的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];
    }