【问题标题】:Move UIBarButtonItems up inside a UIToolbar在 UIToolbar 内向上移动 UIBarButtonItems
【发布时间】:2011-12-30 22:36:49
【问题描述】:
我创建了一个 UIToolbar 的自定义实例来使用背景图像,并且对于我的特定图像,实际的工具栏比图像本身的高度要小(例如,工具栏是 60 像素,而下面的 20 像素是透明的,旁边有一个小物件)。这有点让 UIToolbar 感到困惑,因为所有 UIBarButtonItems 都被强制垂直居中,这与我的图像不对齐。
我可以设置一个边距或什么来让按钮向上滑动吗?我考虑过 UIButton,但我需要一个图像来匹配现有工具栏的外观,所以我更喜欢动态生成按钮。
【问题讨论】:
标签:
iphone
objective-c
uibarbuttonitem
uitoolbar
【解决方案1】:
我不完全确定,但这可能有效:- (void)setBackgroundVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics for UIBarButtonItem 类。
参考:UIBarButtonItem class reference
【解决方案2】:
在最近的 iOS 版本中,我可以使其可靠工作的唯一方法是调整 UIToolbar 的内容视图。在我的UIToolbar 子类中,layoutSubviews 中有以下代码:
if ( _preferredHeight )
{
[self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull v, NSUInteger idx, BOOL * _Nonnull stop) {
NSString* className = NSStringFromClass(v.class);
if ( [className localizedCaseInsensitiveContainsString:@"content"] )
{
v.frame = CGRectOffset( self.bounds, 0, 2 * (44 - self->_preferredHeight) );
*stop = YES;
}
}];
}
请注意,这会在 UIToolbar 私有子视图层次结构中窥视,并且可能不是 AppStore 安全的或在未来的 iOS 版本中中断。