如何更改自定义UINavigationBar类的标签文本

时间:2013-09-22 05:52:37

标签: ios objective-c uinavigationbar

我正在尝试创建自定义导航栏类​​。这是我的代码。问题是如何使用我自己的方法从其他类设置标签文本(navTitleteamName)。喜欢这种方法[self.navigationbar setTitle:@""]

#import "CustomNavigationBar.h"

@implementation CustomNavigationBar

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    [self setBackgroundColor:[UIColor clearColor]];
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIImage *navImage = [UIImage imageNamed:@"nav"];
    CGRect r = CGRectMake(0, 0, 320, 44);
    CGContextDrawTiledImage(context, r, navImage.CGImage);

    UIImageView *teamId = [[UIImageView alloc] initWithFrame: CGRectMake(210, 17, 40, 10)];
    teamId.image = [UIImage imageNamed:@"team"];

    UILabel *navTitle = [[UILabel alloc] initWithFrame: CGRectMake(10, 2, 200, 39)];
    navTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    navTitle.text = @"title";
    navTitle.backgroundColor = [UIColor clearColor];
    navTitle.textColor = [UIColor blackColor];
    navTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];

    UILabel *teamName = [[UILabel alloc] initWithFrame: CGRectMake(255, 18, 78, 10)];
    teamName.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    teamName.backgroundColor = [UIColor clearColor];
    teamName.textColor = [UIColor blackColor];
    teamName.font = [UIFont fontWithName:@"Helvetica-Bold" size:10];

    [self addSubview:teamId];
    [self addSubview:navTitle];
    [self addSubview:teamName];
}

@end

1 个答案:

答案 0 :(得分:0)

首先,像这样添加一个全局变量navTitle:

@implementation CustomNavigationBar
static UILabel *navTitle;

然后在你的drawRect方法中简单地实例化它:

navTitle = [[UILabel alloc] initWithFrame: CGRectMake(10, 2, 200, 39)];

然后在CustomNavigationBar.h

中添加此方法
+(void)setTitle:(NSString *)title;

然后在CustomNavigationBar.m

中添加此内容
+(void)setTitle:(NSString *)title{
    [navTitle setText:title];
}

然后在您的其他类中,只需导入CustomNavigationBar.h并调用方法:

[CustomNavigationBar setTitle:@"myTitle"];