当我尝试将图像用于UIBarButtonItem时,文本不会显示。有没有办法显示文字和图像?
答案 0 :(得分:40)
您可以使用包含图像和文本的自定义视图初始化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];
答案 1 :(得分:11)
我建议使用Storyboard如何做到这一点:
将UIButton和UILabel放入View中。您可以使用约束来调整其位置。你也可以将它放在视图之外,例如,更高或更低(如我的图片)。为UIButton放置默认和突出显示的图像。
复制栏按钮项目并调整其他按钮。添加灵活空间。
创建商店。
完成:)。当您运行应用程序时,您会得到如下工具栏:
P.S。 Here您可以阅读如何使用.xib
创建UIToolbar子类答案 2 :(得分: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;
答案 3 :(得分:2)
Kris Markel的答案是一个良好的开端(仅适用于< iOS7),但如果您使用色调颜色,它会对图像和按钮的突出显示状态起作用。
我创建了一个类别,它将创建一个UIBarButtonItem(leftBarButtonItem),其外观和行为类似于普通的iOS7后退按钮。看看:https://github.com/Zero3nna/UIBarButtonItem-DefaultBackButton
答案 4 :(得分:1)
UIBarButtonItem的快速更新,带有包含图像和文本的自定义视图。
var chatImage: 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)
答案 5 :(得分:0)
带有目标的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)
}
}