1

UIToolbar で使用する必要がある UIBarButtonItem に画像を追加しようとしています。

画像を読み取ってUIImageViewで表示することさえできましたが、それをUIBarButtonItemに追加してからそのアイテムをUIToolbarに追加すると、ツールバーは「空白の白い」スペースをサイズと形状に置き換えます読み込もうとしている画像。

ここに私がしようとしているものがあります。

UIImage *image = [UIImage imageNamed:@"6.png"];

//This is the UIImageView that I was using to display the image so that i know that it is being read from the path specified.  
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 50, image.size.width, image.size.height);
[self.view addSubview:imageView];

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:image forState:UIControlStateNormal];

//This is the first way that I was trying to accomplish the task but i just get a blank white space

//This is the Second way but with the same blank white result.
UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc] initWithCustomView:button2];

NSArray *items = [NSArray arrayWithObjects: systemItem1, nil];

//Adding array of buttons to toolbar
[toolBar setItems:items animated:NO];

//Adding the Toolbar to the view.
[self.view addSubview:toolBar];

あなたの助けは大歓迎です。

ありがとう!

シュマイス・ウル・ハク

4

1 に答える 1

3

UIKitで通常期待する以外に、ボタンのフレームを明示的に設定する必要がある場合があります。多分それはあなたの問題です。

これは、私がカスタムスタイルの戻るボタン用にカテゴリとして書いたものUIBarButtonItemです(ただし、必要な部分をそこから取り出すことができます)。

これはツールバーではなくナビゲーションバーに使用されていることに注意してください。ただし、これも同様であるため、メカニズムは同じであると思いUIBarButtonItemます。なぜならUIToolbar、コンパイル時にIBを使用して正しく取得することができるからです。

#define TEXT_MARGIN 8.0f
#define ARROW_MARGIN 12.0f
#define FONT_SIZE 13.0f
#define IMAGE_HEIGHT 31.0f

+(UIBarButtonItem*)arrowLeftWithText:(NSString*)txt target:(id)target action:(SEL)selector
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *img = [[UIImage imageNamed:@"arrow_left.png"]
        stretchableImageWithLeftCapWidth:15 topCapHeight:0];

    [btn addTarget:target action:selector forControlEvents:UIControlEventTouchDown];

    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btn setContentEdgeInsets:UIEdgeInsetsMake(0.0f,0.0f,0.0f,TEXT_MARGIN)];
    [btn.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:FONT_SIZE]];
    [btn.titleLabel setShadowOffset:CGSizeMake(0.0f,-1.0f)];

    /**** this is the magic line ****/
    btn.frame = CGRectMake(0.0f,0.0f,
        [txt sizeWithFont:[btn.titleLabel font]].width+ARROW_MARGIN+TEXT_MARGIN,
        IMAGE_HEIGHT);

    [btn styleBarButtonForState:UIControlStateNormal withImage:img andText:txt];
    [btn styleBarButtonForState:UIControlStateDisabled withImage:img andText:txt];
    [btn styleBarButtonForState:UIControlStateHighlighted withImage:img andText:txt];
    [btn styleBarButtonForState:UIControlStateSelected withImage:img andText:txt];
    return [[[UIBarButtonItem alloc] initWithCustomView:btn] autorelease];
}

利用方法:

[UIBarButtonItem arrowLeftWithText:@"Back" target:self action:@selector(dismiss)];
于 2010-07-21T13:55:23.753 に答える