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:@"按鈕 1"
style
target
action];
//button1
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"按鈕 2"
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];

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。