如何以编程方式将UIButton添加到工具栏?

时间:2013-04-02 00:40:55

标签: iphone ios xcode ipad

我正在努力将UIButton添加到屏幕底部的工具栏,问题是它似乎没有出现在工具栏的顶部,而是隐藏在它下面。

我试图将其添加到工具栏的代码(以及我的Go Back按钮代码)是;

请忽略坐标,因为它们不是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 个答案:

答案 0 :(得分: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或spacer添加到按钮数组中....根据您的布局需要。

答案 1 :(得分:1)

您正在为视图添加按钮。

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