我正在尝试创建自定义导航栏类。这是我的代码。问题是如何使用我自己的方法从其他类设置标签文本(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
答案 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"];