Iphone 在UIToolbar中居中UIBarButtonim并添加自定义文本

Iphone 在UIToolbar中居中UIBarButtonim并添加自定义文本,iphone,objective-c,ios,cocoa-touch,Iphone,Objective C,Ios,Cocoa Touch,我需要在工具栏的中心添加一个按钮。我已经成功地将按钮添加到工具栏部分。我的问题如下 1.)我需要将这个按钮居中。它应该位于工具栏的中心 2.)显示刷新按钮图像后,我需要一个文本。 toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)]; NSMutableArray* button = [[NSMutableArray alloc] initWithCapacity:1]; UIBarBu

我需要在工具栏的中心添加一个按钮。我已经成功地将按钮添加到工具栏部分。我的问题如下

1.)我需要将这个按钮居中。它应该位于工具栏的中心

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];

我知道这可以在IB中完成,但是我相信如果你想按一个按钮,你需要在两边添加一个固定的或灵活的空间按钮来保持你的按钮在中间。如果你只需要代码就可以做到这一点。。。尝试将按钮夹在两个空格按钮之间。

1。在工具栏项目数组中的工具栏按钮前后添加灵活的间隔符:

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
s的出口集合,并在
-viewDidLoad
中设置
self.toolbarItems

2.要在工具栏中获取自定义内容,可以创建带有自定义视图的工具栏按钮项:

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

是的,我必须通过代码来完成:(.你能给我一个示例代码来演示如何实现这一点吗?好的,我是iOS新手。这是关于
回答(2)
。你说
的意思是
UIView*customView=[UILabel alloc]initWithRect:…]
类似的东西吗?(对不起,我是新手)是的,很抱歉。
UILabel
UIView
的一个子类,因此如果这符合您的需要,请创建一个并使用它。如果您需要更复杂的内容,请创建自己的自定义
UIView
。您也可以在IB中执行此操作;)问题是我需要
uibarbuttonsystememrefresh
,然后是一个文本。既然我将用BarButtonSystemItem保存
initWithBarButtonSystemItem
来添加
refresh logo
,然后我不能说
initWithCustomView
来添加包含标签的
UIView
。系统项不能真正进行自定义--您必须创建第二个项来显示文本,或者使用一个自定义项和您自己的刷新按钮和文本。