[英]IOS Add right button to navigation bar not working
它適用於不帶標簽欄但不帶標簽欄的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;
我在理解您的問題時遇到了一些問題,但是據我所知,似乎您試圖添加按鈕的任何類都沒有保存在UINavigationController
。
我不確定如何實例化此類(ClassX),但應類似以下操作:
ClassX *temp = [[ClassX alloc] init....];
UINavigationController *control = [[UINavigationController alloc] initWithRootViewController:temp];
然后顯示控件視圖。
第一印象,我認為問題是由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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.