如何以编程方式添加条形图按钮

时间:2011-03-24 12:58:52

标签: iphone uiimage uibarbuttonitem

我正在以编程方式创建一个按钮。但它无法修复屏幕。帮我解决这个问题。

截图:

enter image description here

UIImage *image = [UIImage imageNamed:@"request.png"];
UIBarButtonItem *button2;

//[button2 setWidth:55];
button2= [[UIBarButtonItem alloc] initWithImage:image style:UIBarStyleDefault target:self action:@selector(requestButton)];

self.navigationItem.rightBarButtonItem = button2;

[button2 release];

4 个答案:

答案 0 :(得分:4)

我通常这样做:

self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];

[myButton setImage:[UIImage imageNamed:@"button_normal.png"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"button_pressed.png"] forState:UIControlStateHighlighted];
myButton.frame = CGRectMake(0, 0, 121, 36);

[myButton addTarget:self action:@selector(doSomething) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem * aBarButton = [[[UIBarButtonItem alloc] initWithCustomView:myButton] autorelease];

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

答案 1 :(得分:3)

UIImage *image = [UIImage imageNamed:@"request.png"];    
UIButton* requestButton = [UIButton buttonWithType:UIButtonTypeCustom];
[requestButton setImage:image forState:UIControlStateNormal];
[requestButton addTarget:self action:@selector(requestButton) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithCustomView:requestButton];
self.navigationItem.rightBarButtonItem = button2;

答案 2 :(得分:0)

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

[myButton setImage:[UIImage imageNamed:@"request-1.png"] forState:UIControlStateNormal];

myButton.frame = CGRectMake(0, 0, 80, 36);

[myButton addTarget:self action:@selector(requestButton) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem * aBarButton = [[[UIBarButtonItem alloc] initWithCustomView:myButton] autorelease];


self.navigationItem.rightBarButtonItem = aBarButton;



[myButton release];

答案 3 :(得分:0)

我通常创建UIImageView,然后是UITapGestureRecognizer,我将它添加到UIImageView,最后我创建了UIBarbuttonItem:

    //UIImageView where the image is shown
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageName"]];
    imageViewSettings.frame = CGRectMake(0, 0, 25, 25);
    imageViewSettings.contentMode = UIViewContentModeScaleAspectFit;

    //TapGesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodToTrigger)];

    //Adding the gesture to the ImageView
    [imageView addGestureRecognizer:tapGesture];

    //Creating the barButtonItem
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];

    //Finally add the button to the navigationBar
    self.navigationItem.rightBarButtonItem = barButtonItem;