2012-02-11 36 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