如何使用包含彩色图像的按钮自定义UIToolbar?

时间:2011-01-12 08:40:57

标签: iphone objective-c ios cocoa-touch ios-4.2

我对UIToolbar有两个问题:

1:我已经阅读了许多关于如何在UIToolbar中使用带有自定义图像(彩色)按钮的Stackoverflow答案。我试图在UIToolbar的顶部放置一个视图(hack)并将带有图像的按钮放入其中,但是失败了。现在我被卡住了。你怎么能做到这一点?

2:有没有办法让许多按钮同时处于“按下”状态?我想要完成的功能是具有不同种类排序的不同按钮。

2 个答案:

答案 0 :(得分:8)

好的答案解决了......这里是:

Can I have a UIBarButtonItem with a colored image?

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated]; 
    toolbar = [[UIToolbar alloc] init];
    toolbar.barStyle = UIBarStyleDefault;

    //Set the toolbar to fit the width of the app.
    [toolbar sizeToFit];

    //Calculate the height of the toolbar
    CGFloat toolbarHeight = [toolbar frame].size.height;

    //Get the bounds of the parent view
    CGRect rootViewBounds = self.parentViewController.view.bounds;

    //Get the height of the parent view.
    CGFloat rootViewHeight = CGRectGetHeight(rootViewBounds);

    //Get the width of the parent view,
    CGFloat rootViewWidth = CGRectGetWidth(rootViewBounds);

    //Create a rectangle for the toolbar
    CGRect rectArea = CGRectMake(0, rootViewHeight - toolbarHeight, rootViewWidth, toolbarHeight);

    //Reposition and resize the receiver
    [toolbar setFrame:rectArea];

    //Create a button
    UIImage *image = [UIImage imageNamed:@"colorImage.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );    
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:self action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside];    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    [toolbar setItems:[NSArray arrayWithObjects:barButtonItem,nil]];

    //Add the toolbar as a subview to the navigation controller.
    [self.navigationController.view addSubview:toolbar];
}

-(void)myAction{
    NSLog(@"jippiii");
}

答案 1 :(得分:3)

我知道你的第二个要求的答案。

在IB中单击视图并在检查器中检查多次触摸启用。

干杯