UINavigationController UIToolbar中的UISegmentedControl未正确调整大小

时间:2012-02-11 03:59:18

标签: ios ios5

我正在以编程方式将UISegmentedControl添加到UINavigationController的工具栏(我在UITableViewController中)。我希望分段控件看起来不错,而不是填满整个栏。此外,我希望它与视图一起旋转并调整大小。这应该很简单,但我想我错过了一些东西。我实际上让它工作,但这不是干净的代码所以我希望有人可以告诉我哪些设置/方法用于“正确”的实现。

吸气剂:

- (UISegmentedControl*)stockFilterSegmentedControl {
if (!_stockFilterSegmentedControl) {
    _stockFilterSegmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"All",@"Holdings", nil]];
    [_stockFilterSegmentedControl addTarget:self action:@selector(stockFilterControlPressed:) forControlEvents:UIControlEventValueChanged];
    _stockFilterSegmentedControl.selectedSegmentIndex = 0;
    _stockFilterSegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    CGRect newFrame = _stockFilterSegmentedControl.frame;
    newFrame.size.height = self.navigationController.toolbar.frame.size.height * .8;
    _stockFilterSegmentedControl.frame = newFrame;
}

return _stockFilterSegmentedControl;
}

我们插入的地方:

- (NSArray*)navFooterToolbarArray {
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.stockFilterSegmentedControl];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh:)];
return [NSArray arrayWithObjects:flexibleSpace, barButtonItem, flexibleSpace, refresh, nil];    
}

- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Stocks";
self.toolbarItems = [self navFooterToolbarArray];
}

为了使其成功,我必须添加:

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
NSLog(@"Did autorotate.");
CGRect newFrame = self.stockFilterSegmentedControl.frame;
newFrame.size.height = self.navigationController.toolbar.frame.size.height * .8;
self.stockFilterSegmentedControl.frame = newFrame;
}

这样做的正确方法是什么?

谢谢,

达明

2 个答案:

答案 0 :(得分:2)

答案实际上非常简单 - 您将分段控件上的segmentedControlStyle设置为UISegmentedControlStyleBar,它将完美调整大小而不会有任何戏剧性。自动调整掩码按预期工作。

谢谢,

达明

答案 1 :(得分:1)

你应该真正需要的是:

_stockFilterSegmentedControl.frame = CGRectInset(self.navigationController.toolbar.bounds, 5, 5); //set to toolbar rect inset by 5 pixels
_stockFilterSegmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

当视图旋转时,你不必做任何事情,它应该只是自动调整大小以适应autoresizingMask。