如何将UIBarButtonItem同时包含图像和文本?

nod*_*nja 37 cocoa-touch objective-c uibarbuttonitem

当我尝试将图像用于UIBarButtonItem时,不显示文本.有没有办法显示文字和图像?

Kri*_*kel 41

您可以使用包含图像和文本的自定义视图来初始化UIBarButtonItem.这是一个使用UIButton的示例.

UIImage *chatImage = [UIImage imageNamed:@"08-chat.png"];

UIButton *chatButton = [UIButton buttonWithType:UIButtonTypeCustom];
[chatButton setBackgroundImage:chatImage forState:UIControlStateNormal];
[chatButton setTitle:@"Chat" forState:UIControlStateNormal];
chatButton.frame = (CGRect) {
    .size.width = 100,
    .size.height = 30,
};

UIBarButtonItem *barButton= [[[UIBarButtonItem alloc] initWithCustomView:chatButton] autorelease];
self.toolbar.items = [NSArray arrayWithObject:barButton];
Run Code Online (Sandbox Code Playgroud)

  • 没有必要使用背景图像 - 您只需设置UIButton的标题和图像,图像将自动显示在文本的左侧. (5认同)
  • `[self.navigationItem setRightBarButtonItem:barButton animated:YES];` (2认同)

Igo*_*gor 11

我建议使用Storyboard如何做到这一点:

  1. 拖放到ToolBar通常的UIView.它会自动包装到Bar Button Item.在"尺寸检查器"中调整视图宽度.更改视图的背景颜色以清除颜色.

在此输入图像描述

  1. 将UIButton和UILabel放在View中.您可以使用约束来调整其位置.你也可以把它放在一个视图之外,例如,更高或更低(就像在我的图片上).为UIButton放置默认和突出显示的图像.

  2. 复制栏按钮项目并调整其他按钮.添加灵活空间.

  3. 创建网点.

  4. 完成:).当你运行app时,你得到这样的工具栏:

在此输入图像描述

PS 在这里,您可以阅读如何使用.xib创建UIToolbar子类


abb*_*ood 7

Swift 4.2 与目标

extension UIBarButtonItem {
    convenience init(image :UIImage, title :String, target: Any?, action: Selector?) {
        let button = UIButton(type: .custom)
        button.setImage(image, for: .normal)
        button.setTitle(title, for: .normal)
        button.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)

        if let target = target, let action = action {
            button.addTarget(target, action: action, for: .touchUpInside)
        }

        self.init(customView: button)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 添加此行以消除左侧空间:button.imageEdgeInsets = UIEdgeInsets(top:0,left:-13.0,bottom:0,right:0) (3认同)

San*_*tel 6

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;
Run Code Online (Sandbox Code Playgroud)