我在 UIToolbar 上贴了一个标签(根据这个提示:将 UILabel 添加到 UIToolbar)。
但是工具栏左侧有一个按钮,因此灵活的空间使标签偏离中心,这是我想要的位置。我可以以某种方式将此工具栏项居中以使其在工具栏中保持居中吗?
(已经尝试用虚拟固定空间平衡按钮,没有骰子。)
谢谢!
我在 UIToolbar 上贴了一个标签(根据这个提示:将 UILabel 添加到 UIToolbar)。
但是工具栏左侧有一个按钮,因此灵活的空间使标签偏离中心,这是我想要的位置。我可以以某种方式将此工具栏项居中以使其在工具栏中保持居中吗?
(已经尝试用虚拟固定空间平衡按钮,没有骰子。)
谢谢!
就像你做的那样,在你的中心项目的左侧和右侧添加一个灵活的空间项目。然后在最后添加一个固定的空间项,并将宽度设置为左按钮的宽度——大约 28 像素。
UIBarButtonItem *fixedItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL] autorelease];
fixedItem.width = 28;
要在工具栏上居中文本/标题,您可以使用UILabel
如下所示的简单方法:
UILabel *labelTitle = [[UILabel alloc] init];
labelTitle.font =[UIFont fontWithName:@"Helvetica-Bold" size:18];
labelTitle.backgroundColor = [UIColor clearColor];
labelTitle.textAlignment = UITextAlignmentCenter;
labelTitle.userInteractionEnabled = NO;
labelTitle.text = @"Your Title";
[labelTitle sizeToFit];
CGRect labelTitleFrame = labelTitle.frame;
labelTitleFrame.size.width = self.toolbar.bounds.size.width;
labelTitleFrame.origin.y = (self.toolbar.bounds.size.height - labelTitleFrame.size.height) / 2;
labelTitle.frame = labelTitleFrame;
labelTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// Just add UILabel like UIToolBar's subview
[self.toolbar addSubview:labelTitle];
[labelTitle release];
labelTitle = nil;
最简单的方法是将标签放在栏上方,在它的父视图中,并在那里证明它的合理性。
是的,我们可以将工具栏项居中,只需在工具栏中放置两个灵活的空间,例如:
UIBarButtonItem *flexibaleSpaceBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
toolbar.items = [NSArray arrayWithObjects:loginButton,flexibaleSpaceBarButton,toolBarLabel,flexibaleSpaceBarButton, nil];
如果您不使用灵活或固定空间,您可以修改内部 UIToolbar UIStackView 分布如下。请注意,您应该调用toolbar.centerItemsHorizontally()
视图控制器的viewDidLayoutSubviews()
方法。
extension UIView {
func allSubviews() -> [UIView] {
var _allSubviews: [UIView] = []
for subview in self.subviews {
_allSubviews += subview.allSubviews()
_allSubviews.append(subview)
}
return _allSubviews
}
}
extension UIToolbar {
func centerItemsHorizontally() {
allSubviews().forEach { subview in
if let stackView = subview as? UIStackView {
stackView.distribution = .fillEqually
}
}
}
}