我想将自定义图像添加为左侧菜单项。这就是为什么我使用customView其他我得到我的图像但是蓝色。
这就是我实现它的方式:
UIImageView *menuItemImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MenuButton"]];
UIBarButtonItem *leftMenuItemButton = [[UIBarButtonItem alloc] initWithCustomView:menuItemImageView];
[leftMenuItemButton setAction:@selector(menuClicked:)];
[leftMenuItemButton setTarget:self];
self.navigationItem.leftBarButtonItem = leftMenuItemButton;
一切正常,除非我点击我的按钮没有任何反应。它永远不会出现在这个:
- (void)menuClicked:(id)menuClicked {
NSLog(@"%s menuClicked", __PRETTY_FUNCTION__);
}
有人可以帮助我吗?
答案 0 :(得分:0)
此处的问题似乎是使用ImageView
,UIBarButtonItem目标和操作仅在自定义视图为UIButton时有效。
尝试这样的事情
UIButton* someBtn = [UIButton buttonWithType: UIButtonTypeInfoLight];
UIBarButtonItem *leftMenuItemButton = [[UIBarButtonItem alloc] initWithCustomView:someBtn];
[leftMenuItemButton setAction:@selector(menuClicked:)];
[leftMenuItemButton setTarget:self];
self.navigationItem.leftBarButtonItem = leftMenuItemButton;
希望这有帮助
答案 1 :(得分:0)
首先,您需要创建自定义UIButton和UIBarButtonItem
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(menuClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateHighlighted];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
将按钮添加到navigationBar
[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:barButton, nil]];
答案 2 :(得分:0)
感谢n00bprogrammer:
UIBarButtonItem * menuItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"MenuButton"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(menuClicked:)] ;
self.navigationItem.leftBarButtonItem = menuItem;
答案 3 :(得分:0)
两个答案都指向正确的方向。
这就是我的工作方式:
UIButton *showCalendar = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
showCalendar.frame = CGRectMake( 0, 0, 40, 30 );
[showCalendar setImage:[UIImage imageNamed:@"calendar"] forState:UIControlStateNormal];
[showCalendar addTarget:self action:@selector(toggleCalendar) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:showCalendar];
答案 4 :(得分:0)
以下是代码,为您的imageview添加点按手势:
UIImageView *menuItemImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MenuButton"]];
UIBarButtonItem *leftMenuItemButton = [[UIBarButtonItem alloc] initWithCustomView:menuItemImageView];
UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(menuClicked:)];
[menuItemImageView addGestureRecognizer:tapGesture];