0

我正在尝试创建一个自定义导航栏类​​。这是我的代码。问题是如何用我自己的其他类的方法设置标签文本(navTitle和)。teamName喜欢这种方法[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
4

1 回答 1

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"];
于 2013-09-22T07:35:27.777 回答