如何从UIBarButtonItem中删除样式?

时间:2011-11-20 06:02:27

标签: iphone ios cocoa-touch uibarbuttonitem uitoolbar

UIToolbar内的UIBarButtonItem中使用自定义图形时,程序会自动将图形变为白色并应用内部阴影。如何防止这种自动样式并逐字使用我的自定义图形?

screenshot of toolbar

2 个答案:

答案 0 :(得分:1)

这是通常的做法:

UIImage *buttonImage = [UIImage imageNamed:@"myImage.png"];     
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

[myButton setImage:buttonImage forState:UIControlStateNormal];
[myButton setImage:buttonImage forState:UIControlStateHighlighted];

UIBarButtonItem *myBtnItem = [[UIBarButtonItem alloc] initWithCustomView:myButton];

[myButton addTarget:self action:@selector(someSelector:) forControlEvents:UIControlEventTouchUpInside];
[myBtn setFrame:CGRectMake(someX, someY, someWidth, someHeight)];
[self.toolbar setItems:[NSArray arrayWithObjects:someBtnItemOne, myBtnItem, someBtnItemThree, nil]];
[myBtnItem release];

如果这没有帮助,您能否显示用于初始化工具栏和按钮项的代码?

答案 1 :(得分:1)

这是我创建的一个继承自基于图像的UIBarButtonItem的类:

    #import "XXBarButtonImageItem.h"

    @implementation XXBarButtonImageItem

    - (id)initWithFrame:(CGRect)frame 
                  image:(UIImage*)image 
        backgroundImage:(UIImage*)bgImage
    {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button setFrame:frame];

        self = [super initWithCustomView:_button];
        if (self) 
        {
            if (image)
                [_button setImage:image forState:UIControlStateNormal];

            if (bgImage)
                [_button setBackgroundImage:bgImage forState:UIControlStateNormal];

        }
        return self;    
    }

    - (id)initWithFrame:(CGRect)frame 
                  image:(UIImage*)image 
        backgroundImage:(UIImage*)bgImage 
                 target:(id)target 
                 action:(SEL)selector
    {
        self = [self initWithFrame:frame image:image backgroundImage:bgImage];
        if (self)
        {
            [_button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
        }

        return self;
    }

    - (void)dealloc
    {
        [super dealloc];
        [_button release];
    }

    - (void)addTarget:(id)target action:(SEL)selector forControlEvents:(UIControlEvents)controlEvents
    {
        [_button addTarget:target action:selector forControlEvents:controlEvents];
    }

    - (void)setImage:(UIImage *)image forState:(UIControlState)state
    {
        [_button setImage:image forState:state];
    }

    - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
    {
        [_button setImage:image forState:state];
    }

    @end