我尝试过多次修改我的代码,但仍然无法将变量从UIViewController传递给UIView,变量总是返回(null)。
// BPGraphView.h
@interface BPGraphView : UIView
@property (nonatomic, retain) NSString *test;
@end
// BPGraphView.m
#import "BPGraphView.h"
@implementation BPGraphView
@synthesize test;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
NSLog(@"test %@",test);
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
NSLog(@"draw %@", test); // always return (null)
if ([test isEqual:@"something"]) {
[self drawOutLine];
}
}
@end
// BloodPressureViewController.m
- (void)viewDidLoad
{
BPGraphView * graphview=[[BPGraphView alloc] init];
graphview.test = @"something";
}
答案 0 :(得分:1)
在您的代码中:
- (void)viewDidLoad
{
BPGraphView * graphview=[[BPGraphView alloc] init];
graphview.test = @"dd";
}
运行graphview
完成后,变量viewDidLoad
基本上被销毁。永远不会有机会运行drawRect
。
现在的问题是如何在UIViewController中定义BPGraphView
的实例变量。最简单的方法是将BPGraphView添加到视图的xib文件中,并链接到UIViewController中的IBOutlet。通过这种方式,您应该能够分配到测试
@IBOutlet BPGraphView graphview;
- (void)viewDidLoad
{
graphview.test = @"dd";
}
答案 1 :(得分:1)
如果不设置框架,则不会调用drawRect。
BPGraphView * graphview=[[BPGraphView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
graphview.test = @"something";
[self.view addSubview:graphview];
答案 2 :(得分:0)
我试过这个,它运行良好,在你的代码中,drawRect不被称为
BPGraphView * graphview=[[BPGraphView alloc] init];
graphview.test = @"dd";
[graphview drawRect:CGRectMake(0, 0, 0, 0)];