UIToolbar with UISegmentedControl AutoLayout (/ full width)

I have a UIViewController with a UIToolBar below the UINavigationBar and a UITableView below. The only UIBarButtonItem on my UIToolBar is the UISegmentedControl , as in the screenshot below: enter image description here

However, how do I stretch a UISegmentedControl / UIBarButtonItem to populate a UIToolBar , as in the App Store app? enter image description here

Keep in mind that I also support landscape mode, so it should automatically stretch to fit the new width when the device rotates. I was hoping to achieve this with AutoLayout , but as far as I know, I cannot use AutoLayout inside a UIToolBar .

Any suggestions (except replacing the UIToolBar with a UIView )?

+5
source share
2 answers

I created a toolbar with segmented controls inside and then made the 320 segmented control wide. Then I set the flexible layout guides on each side to make the segmented control center. It looks great in a portrait, but the segmented control will not stretch to the landscape.

Portrait (includes installation and IB simulator) enter image description here

Landscape (also includes installation and IB simulator) enter image description here

It seems that the app store has a segmented control that is set to a specific width, and then the view is not allowed to rotate. I understand that you want the segmented control to change the width with the layout, but unfortunately this is not possible with an automatic layout at the moment.

My suggestion would be if you really wanted the segmented control to change the width with rotation, it would be programmatically set the width when the device rotates to landscape.

 - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) { //set segmented control to landscape } if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) { //set segmented control to portrait width } } 

One more thing, if you end up using this material to rotate the device, you still need these flexible struts in IB so that your segmented control is focused on the toolbar

+7
source

You can do this with code. Something like that:

 @interface ViewController () @property (strong, nonatomic) IBOutlet UIToolbar *toolbar; @property (strong, nonatomic) IBOutlet UISegmentedControl *segment; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _segment.translatesAutoresizingMaskIntoConstraints = NO; [_toolbar addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[_segment]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_segment)]]; [_toolbar addConstraint:[NSLayoutConstraint constraintWithItem:_segment attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_toolbar attribute:NSLayoutAttributeCenterY multiplier:1. constant:0.]]; } @end 
+5
source

All Articles