实际上我想将图像和标签作为UIBarButtonItem放在工具栏上,并为该按钮提供可点击的效果。
所以我在这里做的是创建了一个自定义视图并将Image和Label放在同一自定义视图上,最后将此自定义视图放置为UIBarButtonItem CustomView。
但是当我为同一个UIBarButtonItem设置目标和动作时,它没有调用选择器方法。
整个代码如下。
有人能告诉我代码中的错误是什么吗?有没有其他方法来实现相同的????
早期的建议将不胜感激。
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationController setToolbarHidden:NO];
UIView *customView = [[UIView alloc]
initWithFrame:CGRectMake(0,0,self.navigationController.toolbar.frame.size.width,self.navigationController.toolbar.frame.size.height)];
customView.backgroundColor = [UIColor colorWithRed:62.0/255.0 green:187.0/255.0 blue:150.0/255.0 alpha:1.0];
[self.navigationController.toolbar addSubview:customView];
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(60,0,44,44)];
imgView.image = [UIImage imageNamed:@"documentImage.png"];
[customView addSubview:imgView];
UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(104,0,145,44)];
lbl.text = @"Scan Document";
lbl.textAlignment = NSTextAlignmentLeft;
[customView addSubview:lbl];
UIBarButtonItem *bar = [[UIBarButtonItem alloc]initWithCustomView:customView];
bar.target = self;
bar.action = @selector(scanDocument);
self.toolbarItems = [NSArray arrayWithObjects:bar, nil];
}
答案 0 :(得分:0)
如果要在右侧创建按钮,请输入代码。我已经实现了它并且工作正常。
//Button Right side
UIImage *imgFavRest = [UIImage imageNamed:@"documentImage.png"];
UIButton *cart = [UIButton buttonWithType:UIButtonTypeCustom];
[cart setImage:imgFavRest forState:UIControlStateNormal];
cart.frame = CGRectMake(0, 0, imgFavRest.size.width, imgFavRest.size.height);
[cart addTarget:self action:@selector(showCart) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:cart];
self.navigationItem.rightBarButtonItem = rightBtn;
然后使用这样的方法。这都是
-(void)cartItemCount{
// Method
}
答案 1 :(得分:0)
float textwidth = 50; // according to your text
UIImage *image = [UIImage imageNamed:@"logout"];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.bounds = CGRectMake( 10, 0, image.size.width+textwidth, image.size.height );
[btn addTarget:self action:@selector(scanDocument) forControlEvents:UIControlEventTouchUpInside];
[btn setImage:image forState:UIControlStateNormal];
[btn setTitle:@"test" forState:UIControlStateNormal];
[btn setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 5.0, 0.0, 0.0)];
//Adjust the coordinates and size of your button as your requirement.This is a sample code to guide you.
//PS:Take a UIButton in the nib file>Make it a custom button>Connect the IBOutlet to your custom button in the nib file.Thats it.
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = rightButton;
我看到非常复杂的答案,所有人都使用代码。但是,如果您使用的是Interface Builder,则有一种非常简单的方法:
您甚至可以通过代码使用相同的方法,而不像其他解决方案那样在内部创建UILabel和UIImage。永远保持简单!
编辑:附上一个小例子,其中包含3个设置(标题,图像和背景)的正确插图按钮预览
注意:: UIBarButtonItem
继承自UIBarItem
和NSObject
,所以它对触摸一无所知。如果文档提到动作和目标属性仅在自定义视图为UIButton
时适用,那将是很好的。