2011-12-29 74 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

相關問題