2012-02-11 88 views
0

我正在以编程方式将UISegmentedControl添加到UINavigationController的工具栏(我在UITableViewController中)。我希望分段控制看起来很体面,而不是填满整个酒吧。另外,我希望它随视图旋转并调整大小。这应该很容易,但我想我错过了一些东西。我实际上已经掌握了它的工作原理,但这不是干净的代码,所以我希望有人能告诉我哪些设置/方法用于“适当的”实现。UINavigationController中的UISegmentedControl UIToolbar未正确调整大小

消气:

- (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

答案其实很简单 - 您将分段控件上的segmentedControlStyle设置为UISegmentedControlStyleBar,并且它将在没有任何戏剧性的情况下完美调整大小。自动调整蒙版按预期工作。

感谢,

达明

+0

自iOS 7以来,它不再工作。是否有任何其他iOS 7和更高版本的解决方案? – Vinh 2014-05-30 09:02:02

+0

确认,在iOS7中不起作用 – malex 2014-08-11 15:46:15

1

所有你应该真正需要的是这样的:

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

然后,您就不必做任何事情当视图旋转时,它应该只是自动调整以适应由于autoresizingMask。

+0

的自动尺寸面具没有做什么,我会想到,这是相对于容器视图(工具栏在这种情况下)的框架调整。好吧。我的代码有效,我希望每次旋转时都有更好的方法来设置框架。 +1指出CGRectInset - 虽然我从来没有见过,它可能是有用的。在这里,我宁愿调整高度,即使在旋转时也保持宽度不变。谢谢! – 2012-02-11 10:09:24

相关问题