当我尝试对 UIBarButtonItem 使用图像时,不显示文本。有没有办法同时显示文字和图像?
您可以使用具有图像和文本的自定义视图来初始化 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];
我建议一种使用故事板来做到这一点的方法:
将 UIButton 和 UILabel 放入 View 中。您可以使用约束来调整它们的位置。您也可以将其放在视图之外,例如稍高或稍低(如我的图片所示)。为 UIButton 放置默认图像和突出显示图像。
复制栏按钮项目并调整其他按钮。添加灵活空间。
创建销售点。
完成:)。当你运行应用程序时,你会看到这样的工具栏:
附注在这里您可以阅读如何使用 .xib 创建 UIToolbar 子类
带有目标的 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)
}
}
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;
Kris Markel 的回答是一个好的开始(仅 < iOS7), but if you use tint color, it wount work for the image and the highlighted state of the button.
我创建了一个类别,它将创建一个 UIBarButtonItem (leftBarButtonItem),其外观和行为类似于普通的 iOS7 后退按钮。看一下:https://github.com/Zero3nna/UIBarButtonItem-DefaultBackButton
快速更新 UIBarButtonItem 具有包含图像和文本的自定义视图。
var rightImage: UIImage = UIImage(named: "YourImageName")
var rightButton : UIButton = UIButton(type: UIButtonType.custom)
rightButton.setBackgroundImage(rightImage, for: .normal)
rightButton.setTitle(title, for: .normal)
rightButton.frame.size = CGSize(width: 100, height: 30)
let menuUIBarButtonItem = UIBarButtonItem(customView: rightButton)