2011-12-29 40 views
4

我需要在ToolBar的中心添加一个按钮。我已经成功地将按钮添加到工具栏部分。我的问题如下:在UIToolbar中居中放置UIBarButtonItem并添加自定义文本

1.)我需要居中这个barbutton。它应该在工具栏的中心

2.)我需要在显示刷新按钮图像后有文本。

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)]; 

    NSMutableArray* button = [[NSMutableArray alloc] initWithCapacity:1]; 

    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonAction:)]; 

    [button addObject:barButton]; 

    [toolBar setItems:button animated:NO]; 

    [self.view addSubview:toolBar]; 

回答

1

我知道这可以在IB做,但我相信,如果要居中的按钮,你将需要添加任何一方固定或者灵活的空间按钮,让您的按钮在中间。如果你打算用代码来做到这一点......尝试将按钮夹在2个空格按钮之间。

+0

是的,我有代码:(做到这一点你能告诉我一个示例代码说明如何实现这一点? – sharon 2011-12-29 15:40:51

17

之前和工具栏项目阵列中的栏按钮后添加柔性间隔:

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)]; 

UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonAction:)]; 

NSArray *toolbarItems = [NSArray arrayWithObjects:flexibleSpace, barButton, flexibleSpace]; 

[toolBar setItems:toolbarItems animated:NO]; 

[self.view addSubview:toolBar]; 

配置工具栏是很容易在Interface Builder做的。如果您的视图控制器位于UINavigationController堆栈内,则仍然可以使用IB创建UIBarButtonItem的插座集合,并在-viewDidLoad中设置self.toolbarItems

2.为了得到一个工具栏自定义内容,您可以创建自定义视图栏按钮项:

UIView *customView = <# anything, could be a UILabel #>; 
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customView]; 
+0

好的,我是iOS的新手,这是关于'answer(2)'。通过说'<#任何东西,可以是UILabel#>'你的意思是'UIView * customView = [ UILabel alloc] initWithRect:....]'这样的东西??(对不起,我是一个新手) – sharon 2011-12-29 15:55:17

+0

对不起,'UILabel'是'UIView'的子类,所以如果这符合你的需求,创建一个并使用它如果你需要更复杂的东西,建立你自己的'UIView' 。你也可以在IB中做到这一点;) – 2011-12-29 16:00:01

+0

那么问题是我需要'UIBarButtonSystemItemRefresh'后跟一个文本。所以你的方法会工作,因为我将保存'initWithBarButtonSystemItem'来添加'refresh logo',然后我不能说'initWithCustomView'来添加包含标签的'UIView'。 – sharon 2011-12-29 16:33:36

相关问题