如何使用图像和标签制作自定义UIBarButtonItem? [英] How to make custom UIBarButtonItem with image and label?
本文介绍了如何使用图像和标签制作自定义UIBarButtonItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个包含图像和文本的自定义UIBarButtonItem,如下所示:
I would like to make a custom UIBarButtonItem that contains both image and text, something like this:
我尝试了对UIBarButtonItem进行子类化并重写此方法:
I tried subclassing UIBarButtonItem and overriding this method:
- (UIView *)customView
{
if (!self.storedView) {
UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 44)];
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:self.image];
tempImageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 100, 44)];
tempLabel.text = @"text";
[temp addSubview:tempImageView];
[temp addSubview:tempLabel];
self.storedView = temp;
}
return self.storedView;
}
我这样使用它:
UIBarButtonItem *left = [[LeftItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsPressed)];
left.title = @"Settings";
left.image = [UIImage imageNamed:@"settings.png"];
self.navigationItem.leftBarButtonItem = left;
但是使用这个我只得到图像,但不是标签。我做错了什么?
But using this I only get the image, but not label. What am I doing wrong?
推荐答案
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[button addTarget:target action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 31)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
[label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:13]];
[label setText:title];
label.textAlignment = UITextAlignmentCenter;
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[button addSubview:label];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;
这篇关于如何使用图像和标签制作自定义UIBarButtonItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文