【问题标题】:How to add a custom button to a UINavigationBar (a la Foursquare)如何将自定义按钮添加到 UINavigationBar (a la Foursquare)
【发布时间】:2012-07-02 03:13:03
【问题描述】:

我正在经历创建自定义 UINavigationBar 的不同选项,由于我的应用是 iOS 5+,我正在使用此代码:

// Set the background image all UINavigationBars
[[UINavigationBar appearance]  setBackgroundImage:NavigationPortraitBackground 
                                    forBarMetrics:UIBarMetricsDefault];

现在我想在最右侧有一个自定义图像按钮,我有点迷失了。我应该采用另一种方式,将 UINavigationBar 子类化并为其添加一个按钮,还是有更简单的方法?

【问题讨论】:

  • 不,我不是,我设法设置了 rightBarButtonItem,但我无法设置定位,所以我运气不佳

标签: ios ios5 uinavigationcontroller uinavigationbar


【解决方案1】:

绝对是这个东西的子类。 UINavigationBar 易于继承,但很难放入导航控制器。我将向您展示我的子类(CFColoredNavigationBar),它还免费提供任意颜色的背景。

//.h
#import <UIKit/UIKit.h>

@interface CFColoredNavigationBar : UINavigationBar

@property (nonatomic, strong) UIColor *barBackgroundColor;
@property (nonatomic, strong) UIButton *postButton;
@end
//.m
#import "CFColoredNavigationBar.h"

@implementation CFColoredNavigationBar
@synthesize barBackgroundColor = barBackgroundColor_;
@synthesize postButton = postButton_;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
-(void)awakeFromNib {
    postButton_ = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.frame)-60, 0, 60.0f, CGRectGetHeight(self.frame))];
    [postButton_ setImage:[UIImage imageNamed:@"Post.png"] forState:UIControlStateNormal];
    [self addSubview:postButton_];
}
- (void)drawRect:(CGRect)rect {
    if (barBackgroundColor_ == nil) {
        barBackgroundColor_ = [UIColor blackColor];
    }
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetFillColorWithColor(context, [barBackgroundColor_ CGColor]);
    CGContextFillRect(context, CGRectInset(self.frame, 0, self.frame.size.height*-2));
}

@end

【讨论】:

  • 最好的部分,这东西与操作系统版本无关。应该可以一直工作到 2.0
  • 现在我从笔尖设置了自定义导航栏,因此不会调用 initWithFrame。在这方面我怎么能这样做?或者,如果您可以分享您如何在导航控制器中实现自定义导航栏,那也很棒:)
  • 使用我在 initWithNibName: 中提供的代码并将其移至 awakeFromNib。简单的!我的方法也是基于xib的。我会编辑这个。
  • 当然。经过多次试验和错误,我自己想通了,不妨让未来的访问者不必。
  • 我还是一头雾水,如何将这个自定义导航栏设置为导航控制器的导航栏?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多