I have a nice UIToolbar
subclass I just wrote to do this, thanks to the code in Oded's post. It works fine for a toolbar with 5 items: button, flex space, textfield, flex space, button. By overriding layoutSubviews
, it can properly adjust the UITextField
width:
@implementation AdaptingTextFieldToolbar
- (void)layoutSubviews
{
CGFloat totalItemsWidth = 0.0;
CGFloat itemsMargin = 8.0;
UIBarButtonItem *textFieldBarButtonItem;
for (UIBarButtonItem *barButtonItem in self.items) {
// Get width of bar button item (hack from other SO question)
UIView *view = [barButtonItem valueForKey:@"view"];
if(view) {
if([view isKindOfClass:[UITextField class]]) {
textFieldBarButtonItem = barButtonItem;
} else
if(view.bounds.size.width > 0) {
// Docs say width can be negative for variable size items
totalItemsWidth += view.bounds.size.width + itemsMargin;
}
}
totalItemsWidth += itemsMargin;
}
textFieldBarButtonItem.width = (self.bounds.size.width - totalItemsWidth) - itemsMargin;
NSLog(@"WIDTH=%f", textFieldBarButtonItem.width);
[super layoutSubviews];
}
@end