如何使用图像和标签制作自定义UIBarButtonItem?

时间:2013-09-17 08:16:41

标签: ios objective-c ios7

我想创建一个包含图像和文本的自定义UIBarButtonItem,如下所示:

enter image description here

我尝试了对UIBarButtonItem进行子类化并重写此方法:

- (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;

但是使用这个我只得到图像,但不是标签。我做错了什么?

12 个答案:

答案 0 :(得分:99)

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;

答案 1 :(得分:22)

您可以向UIBarButtonItem添加自定义视图。

在iOS 7中,UIButtonTypeSystem有一个名为UIButton的新buttonType,可用于您的目的。 试试这个,

UIView* leftButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];

UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
leftButton.backgroundColor = [UIColor clearColor];
leftButton.frame = leftButtonView.frame;
[leftButton setImage:[UIImage imageNamed:<YourImageName>] forState:UIControlStateNormal];
[leftButton setTitle:@"YourTitle" forState:UIControlStateNormal];
leftButton.tintColor = [UIColor redColor]; //Your desired color.
leftButton.autoresizesSubviews = YES;
leftButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
[leftButton addTarget:self action:@selector(<YourTargetMethod>) forControlEvents:UIControlEventTouchUpInside];
[leftButtonView addSubview:leftButton];

UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:leftButtonView];
self.navigationItem.leftBarButtonItem = leftBarButton;

更新了 Swift 代码,

let leftButtonView = UIView.init(frame: CGRect(x: 0, y: 0, width: 110, height: 50))

let leftButton = UIButton.init(type: .system)
leftButton.backgroundColor = .clear
leftButton.frame = leftButtonView.frame
leftButton.setImage(UIImage.init(imageLiteralResourceName: <YourImageName>), for: .normal)
leftButton.setTitle("YourTitle", for: .normal)
leftButton.tintColor = .red //Your desired color.
leftButton.autoresizesSubviews = true
leftButton.autoresizingMask = [.flexibleWidth , .flexibleHeight]
leftButton.addTarget(self, action: #selector(<YourTargetMethod>), for: .touchUpInside)
leftButtonView.addSubview(leftButton)

let leftBarButton = UIBarButtonItem.init(customView: leftButtonView)
navigationItem.leftBarButtonItem = leftBarButton

答案 2 :(得分:14)

如果您的BarButtonItem位于Storyboard中,您可以将另一个Button拖动到BarButtonItem中,因此BarButtonItem中会有一个Button,您可以将该图像和标签添加到该按钮。

答案 3 :(得分:12)

SWIFT版

    let button =  UIButton(type: .Custom)
    button.setImage(UIImage(named: "icon_right"), forState: .Normal)
        button.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
    button.frame = CGRectMake(0, 0, 53, 31)
    button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
    let label = UILabel(frame: CGRectMake(3, 5, 50, 20))
    label.font = UIFont(name: "Arial-BoldMT", size: 16)
    label.text = "title"
    label.textAlignment = .Center
    label.textColor = UIColor.whiteColor()
    label.backgroundColor =   UIColor.clearColor()
    button.addSubview(label)
    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = barButton

答案 4 :(得分:4)

接受答案的问题是UIBarButtonItem文字在突出显示时不会改变。下面的代码将显示文本和图像。 UIEdgeInsetsMake将文本向左移动,图像向右移动。

UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(myButtonEvent:) 
             forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 32)];

[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] 
                 forState:UIControlStateNormal];
[button setTitleColor:[UIColor lightGrayColor] 
                 forState:UIControlStateHighlighted];
button.titleEdgeInsets = UIEdgeInsetsMake(-2, -20, 2, 20);
button.titleLabel.font = font;
button.titleLabel.textAlignment = NSTextAlignmentLeft;

UIImage *image = [UIImage imageNamed:@"imageName"];
[button setImage:image 
        forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32);
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];

答案 5 :(得分:4)

在UIBarButtonItem中使用UIButton作为自定义视图。您可以使用-setImage:forState:-setTitle:forState:

创建所需的UIButton,包括图片和文字
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[button setTitle:@"Settings" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButtonItem;

只需将UIButton拖动到导航栏上的左侧栏按钮插槽,即可使用界面构建器完成此操作。

答案 6 :(得分:3)

我发布了一个处理色彩和图像的答案,类似于普通的uibarbuttonitem ...... https://stackoverflow.com/a/28348461/925135

答案 7 :(得分:3)

使用NSAttributedString的另一种方法:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Button Text"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"buttonImage"];
textAttachment.bounds = CGRectMake(0, -3, textAttachment.image.size.width, textAttachment.image.size.height); //the origin y value depends on the size of the image to get a perfect fit
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(0, 0) withAttributedString:attrStringWithImage]; // Adding the image at the beginning
[customButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[customButton sizeToFit];
[customButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:customButton];

答案 8 :(得分:2)

UIImage *image = [UIImage imageNamed:@"icon.png"];
UIImage *backgroundSelected = [UIImage imageNamed:@"icon_selected.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(ButtonTapped:event:)forControlEvents:UIControlEventTouchUpInside]; //adding action
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setBackgroundImage:backgroundSelected forState:UIControlStateSelected];
button.frame = CGRectMake(0 ,0,35,35);

然后将该按钮设为自定义按钮

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;

答案 9 :(得分:2)

这是针对Swift 3的Maturegooseberry答案的更新版本

    let button =  UIButton(type: .custom)
    button.setImage(UIImage(named: "icon_right"), for: .normal)
    button.addTarget(self, action: Selector(("buttonAction")), for: .touchUpInside)
    button.frame = CGRect(x: 0, y: 0, width: 53, height: 31)
    button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
    let label = UILabel(frame: CGRect(x: 3, y: 5, width: 50, height: 20))
    label.font = UIFont(name: "Arial-BoldMT", size: 16)
    label.text = "title"
    label.textAlignment = .center
    label.textColor = UIColor.white
    label.backgroundColor =   UIColor.clear
    button.addSubview(label)
    let barButton = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = barButton

答案 10 :(得分:1)

很棒的解决方案!我想在UIToolbar中添加一个UISlider,我就是这样做的!不要忘记通过以下方式为自定义按钮添加目标操作:

  customButton.targetForAction(#selector(addTapped), withSender: self)

这样你可以控制按钮:)

答案 11 :(得分:1)

这是我根据先前答案得出的解决方案。可能会有所帮助。

def remove_letters(word,letter):
    return word.replace(letter,'')