带有图像和标题的 iOS 7 BarButtonItem [英] iOS 7 BarButtonItem with image and title

查看:12
本文介绍了带有图像和标题的 iOS 7 BarButtonItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何才能实现这样的目标:

I'm trying to figure out how can I achieve something like this:

这是一个工具栏,我想保留按钮标题文本,而不必创建带有图标和文本的整个图像.如何在保持文本设置的同时将图标添加到 UIBarButtonItem 的左侧:

This is a toolbar and I'd like to keep the button title text without having to create the whole image with icon AND text. How can I add the icon to the left of the UIBarButtonItem while keeping the text set with:

UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Button" style:UIBarButtonItemStyleBordered target:nil action:nil];

编辑

这是我用以下代码实现的:

This is what I achieved with the following code:

    UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customButton setImage:[UIImage imageNamed:@"Test"] forState:UIControlStateNormal];
    [customButton setTitle:@"Button" forState:UIControlStateNormal];
    customButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [customButton sizeToFit];
    UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];

这里有两个问题:第一个是 UIButton 的大小,第二个是,正如您从 gif 中看到的,当我点击按钮内部时,按钮无法正确设置动画当我松开水龙头时.有什么想法吗?

Two issues here: the first is the size of the UIButton and the second is that, as you can see from the gif, the button doesn't animate properly when I tap inside the button and when I release the tap. Any ideas?

推荐答案

您可以将 UIButton 作为自定义视图嵌入到 UIBarButtonItem 中.您可以使用 -setImage:forState:-setTitle:forState:.

You can embed a UIButton as a custom view inside your UIBarButtonItem. You can create your UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:.

UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
[customButton setTitle:@"Button" forState:UIControlStateNormal];
[customButton sizeToFit];
UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem

请注意,执行此操作时,您需要将 IBAction 方法附加到 customButton,而不是 customBarButtonItem.

Note that when doing this, you'll need to attach your IBAction methods to customButton, not to customBarButtonItem.

有关更多信息,请参阅initWithCustomView: 的文档.

For more info, see the documentation for initWithCustomView:.

您还可以在界面构建器中完成所有这些操作,只需将 UIButton 拖动到导航栏上的左侧栏按钮/右侧栏按钮槽即可.

You can also do all of this in interface builder just by dragging a UIButton to the left bar button/right bar button slot on a navigation bar.

这篇关于带有图像和标题的 iOS 7 BarButtonItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆