How can I use a segmented space fill item on a toolbar in an iOS app?

I have a segmented control. Whenever a view completes, I create a toolbar button element to hold it and set it as a toolbar item. The problem I am facing is that the segmented control does not fill the gap in the toolbar, even if it is configured to fill the space behavior.

How can I use a segmented element to fill in the gaps in a toolbar in an iOS app?

+6
source share
2 answers

It looks like you are trying to get custom toolbar behavior from UIToolbar. Why not just leave the UIView there and populate it with the UISegmentedControl in the usual way? Are there any specific UIToolbar features you need?

+1
source

There is no β€œspace-filling behavior" at all in UIView. They get the size that they are assigned. All you can do is:

  • set the autoresist mask to control how they change if their parent view resizes
  • set a UIViewContentMode to control how they resize their content (important for UIImageViews, for example)

In your case, you can do the following to get a UIToolbar containing a UISegmentedControl that is as wide as a toolbar:

(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 items UIBarButtonItem *myBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:mySegmentedControl]; myToolbar.items = [NSArray arrayWithObject:myBarButtonItem]; } 
0
source

Source: https://habr.com/ru/post/914684/


All Articles