2

它适用于没有标签栏但不适用于标签栏的 ViewController。此外,这是故事板中的第一个视图控制器。

UIImage *bookmarkImage = [UIImage imageNamed:@"bookmark"];

//create the button and assign the image
UIButton *bookmarkButton = [UIButton buttonWithType:UIButtonTypeCustom];

 //set the frame of the button to the size of the image (see note below)
bookmarkButton.frame = CGRectMake(100, 0, bookmarkImage.size.width,      bookmarkImage.size.height);
        [bookmarkButton setImage:bookmarkImage forState:UIControlStateNormal];

bookmarkButton addTarget:self action:@selector(addFavorite:) forControlEvents:UIControlEventTouchUpInside];
bookmarkButton.imageView.contentMode=UIViewContentModeScaleAspectFit;

//create a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem2 = [[UIBarButtonItem alloc] initWithCustomView:bookmarkButton];
self.navigationItem.rightBarButtonItem = customBarItem2;
4

2 回答 2

1

我在理解您的问题时遇到了一些问题,但据我所知,您尝试添加按钮的任何课程似乎都没有保存在UINavigationController.

我不确定你如何实例化这个类(ClassX),但它应该类似于这样:

ClassX *temp = [[ClassX alloc] init....];

UINavigationController *control = [[UINavigationController alloc] initWithRootViewController:temp];

然后显示控件视图。

于 2012-07-27T21:36:49.343 回答
0

第一印象,我认为问题是由 引起的UIButton *bookmarkButton = [UIButton buttonWithType:UIButtonTypeCustom];,但我不太确定。如果你愿意,你可以像这样修改。它确实有效。

- (void)viewDidLoad
{
    [super viewDidLoad];
    navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    UINavigationItem *navigationItem = [[[UINavigationItem alloc] initWithTitle:@"My NavigationBar"] autorelease];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 70, 30)];

    [button setImage:[UIImage imageNamed:@"bookmark.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked)
     forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc]
                                   initWithCustomView:button];

    navigationItem.rightBarButtonItem = buttonItem;
    [navigationBar pushNavigationItem:navigationItem animated:NO];
    [self.view addSubview:navigationBar];

    [buttonItem release];
    [button release];
}
于 2012-07-27T22:49:00.430 回答