2013-04-02 88 views
-2

我很努力地將UIButton添加到屏幕底部的工具欄中,問題在於它看起來並不在工具欄的頂部,而隱藏在它的下面。如何以編程方式將UIButton添加到工具欄上?

工具欄的代碼我試圖將它添加到(以及我的回退按鈕代碼下面)是;

請忽略座標,因爲它們不是100%,但iPhone版本至少應該顯示在工具欄上,因爲它在同一區域附近,我可以在之後進行調整。

//Insert Main Toolbar On Main View 
    if (IS_IPHONE_5) { 

      //offsetY = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 6 : 6 * 2; 

     offsetY = (1136 - 960)/2; 

     frameRect = CGRectMake(0, SCREEN_HEIGHT - 53, 320 * 2, 53); 

    }else if (IS_IPHONE || IS_IPHONE_4) { 
      offsetY = 0; 
      frameRect = CGRectMake(0, SCREEN_HEIGHT - 53, 320 * 2, 53); 

    } else { 

     frameRect = CGRectMake(0, 1024 - 53 * 2, 768 * 2, 53 * 2); 
    } 

    offsetY = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 6 : 6 * 2; 

    main_toolbar = [[UIImageView alloc] initWithFrame:frameRect]; 
    [main_toolbar setImage:[UIImage imageNamed:[g_AppUtils resourceNameForDevice:@"ToolbarBackground" ofType:@"png"]]]; 
    main_toolbar.userInteractionEnabled = YES; 
    [self.view addSubview:main_toolbar]; 
    [main_toolbar release]; 

    //Insert Go Back Button On Main Toolbar 
    goHome_button = [[UIButton alloc] initWithFrame:frameRect]; 
    goHome_button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    [goHome_button setImage:[UIImage imageNamed:@"BackButton.png"] forState:UIControlStateNormal]; 

    [goHome_button addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { 
     goHome_button.frame = CGRectMake(55, 410, 46, 42); 
    } else { 
     goHome_button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
    } 

    [main_toolbar addSubview:goHome_button]; 
    [self.view addSubview:goHome_button]; 

希望有任何幫助。

回答

2

您需要使用initWithCustomView創建一個UIBarButtonItem來將UIButton關聯到它。接下來將所有的酒吧按鈕項添加到UIToolBar的setItems方法。事情是這樣的:

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:myButton]; 
[buttons addObject:barButton]; // buttons is a NSMutableArray 
[mainToolBar setItems:buttons animated:YES]; 

對於間距:

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

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] 
           initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace 
           target:nil 
           action:nil]; 
[spacer setWidth:50]; // 50 just an example 

添加spcerFlex或間隔成按鍵陣列....每佈局需要。

+0

非常感謝! :) – user1695971

1

您正在將按鈕添加到您的視圖。

... 
[main_toolbar addSubview:goHome_button]; 
[self.view addSubview:goHome_button]; <--- Remove this line 
+0

當然該框架是錯誤的,然後需要適應 –

+0

如果我刪除該行,沒有圖像出現了。 如果我保留該行並刪除[main_toolbar行,它會出現在工具欄後面:/ – user1695971

相關問題