banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

iOS开发之UIToolbar和UINavigationBar的UIBarButtonItem的距离调整

ios 开发过程中,往 UIToolbar 和 UINavigationBar 中添加的多个 UIBarButton 距离通常是固定不可以调整的, 比如在 UINavigationBar 的右侧添加两个以上 UIBarButton 时,两个 UIBarButton 加上中间的空白占据了和大一部分的空间, 因而在开发 iPhone 应用程序时,开发者通常使用 UISegmentedControl 来替代使用两个 button。

其实如果利用一下 UIToolbar 的一些特性就可以实现对的 UIBarButton 的间距调整,方法如下: 1. 定义一个 UIToolbar 来存放者两个 button 2. 在两个 Button 之间添加一个 UIBarButtonSystemItemFlexibleSpace 类型的 button 3. 调整 UIToolbar 的宽度,这时就可以直接调整两个 button 之间的空白宽度了 4. 将 UIToolbar 添加到 Navigationbar 中去即可

其中的第 4 步,采用早期 ios4 时候添加多个 UIBarButton 到 UIToolbar 和 UINavigationBar 的方法即可

实现代码如下

//button1
UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button1"
style
target
action];
//button1
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"Button2"
style
target
action];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem
target
action];
// 初始化 toolbar
UIToolbar *rightToolbar = [[UIToolbar alloc]init];
rightToolbar.items = [NSArray arrayWithObjects,space,button2,nil];

// 使 button 的 tint 色与导航条一致
rightToolbar.tintColor = self.navigationController.navigationBar.tintColor;
// 调整宽度使 button 间距缩小
rightToolbar.frame = CGRectMake(220, 0, 101, 44);

// 移除背景,用于添加到 UIToolbar 或 UINavigationBar 中
rightToolbar.backgroundColor = [UIColor clearColor];
for (UIView *view in [rightToolbar subviews]) {
if ([view isKindOfClass:[UIImageView class]]) {
[view removeFromSuperview];
}
}
// 添加到 navigationbar 中
[self.navigationController.visibleViewController.navigationController.navigationBar addSubview];

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.