我有一個好UIToolbar
子類,我只是寫要做到這一點,得益於俄德的職位代碼。它適用於包含5個項目的工具欄:按鈕,彈性空間,文本框,彈性空間,按鈕。通過覆蓋layoutSubviews
,可適當調整UITextField
寬度:
@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
這不會考慮到其他按鈕 - 即長標籤將超過其合理限度... – 2012-06-04 06:14:06
這飛馳的工作爲我的文本字段有按鈕在右邊。乾杯! – Joey 2014-05-15 16:18:41