2

Is it somehow possible to get a UIBarButtonItem with a custom view containing a UISlider to automatically resize similarly to a UIBarButtonItem using the system style UIBarButtonSystemItemFlexibleSpace?

For example (for the sake of brevity I've left out setting frames and adding the toolbar as a subview to an existing view)

UISlider *slider = [UISlider new];
slider.minimumValue = 0;
slider.maximumValue = 1;
slider.value = 0.5

UIBarButtonItem *sliderItem = [[UIBarButtonItem alloc] initWithCustomView:slider];
UIBarButtonItem *exampleItem = [[UIBarButtonItem alloc] initWithTitle:@"Example" style:UIBarButtonItemStylePlain target:nil action:nil];

UIToolbar *toolbar = [UIToolbar new];
toolbar.items = @[sliderItem, exampleItem];

The idea being the toolbar is the full width of the screen, exampleItem can be a variable width due to localisation of it's title, and slideItem resizes similarly to UIBarButtonSystemItemFlexibleSpace to take up the remaining space in the toolbar.

But the results are instead the slider stays taking up what ever frame you've given it (or the default/minimum frame if left out) and the next button just sits up against it.

I've tried the method mentioned in the following answer make a UIBarButtonItem with customView behave like Flexible-Space item by changing the auto resizing mask of the slider, but it appears not to work (the question is about using a UITextField not a UISlider which is probably why.)

I've also tried using another UIView containing the UISlider as the custom view to intercept any sizeThatFits calls, but it in fact never gets called as I suspected.

Community
  • 1
  • 1
Philip
  • 769
  • 7
  • 20
  • I don't think you can do this without calculating the sizes of the button and spaces, and setting the slider's frame accordingly. Is there a reason you can't use a custom view rather than a UIToolBar so you can do this with constraints? – rdelmar Oct 03 '14 at 23:18
  • No there isn't a reason it could not be done that way really, I just assumed this might be a simple way of doing it having the UIToolbar handle most of it for you, but I guess that's not the case. – Philip Oct 03 '14 at 23:56

0 Answers0