它适用于没有标签栏但没有标签栏的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;
答案 0 :(得分:1)
我在理解你的问题时遇到了一些问题,但是从我可以收集的情况来看,似乎你试图添加按钮的课程并不是UINavigationController
。
我不确定你如何实例化这个类(ClassX),但应该这样做:
ClassX *temp = [[ClassX alloc] init....];
UINavigationController *control = [[UINavigationController alloc] initWithRootViewController:temp];
然后显示控件视图。
答案 1 :(得分: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];
}