【问题标题】:Passing variable From UIViewController to UIView将变量从 UIViewController 传递给 UIView
【发布时间】:2014-10-15 02:32:38
【问题描述】:

我多次尝试修改我的代码,但仍然无法将变量从 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";
}

【问题讨论】:

    标签: ios objective-c iphone xcode xcode6


    【解决方案1】:

    在您的代码中:

    - (void)viewDidLoad
    {
    BPGraphView * graphview=[[BPGraphView alloc] init];
    graphview.test = @"dd";
    }
    

    一旦viewDidLoad 运行完成,变量graphview 基本上就被销毁了。它永远不会有机会运行drawRect

    现在的问题是如何在 UIViewController 中定义 BPGraphView 的实例变量。最简单的方法应该是将 BPGraphView 添加到视图的 xib 文件中,并链接到 UIViewController 中的 IBOutlet。这样,你应该可以分配给测试了

    @IBOutlet BPGraphView graphview;
    
    
    - (void)viewDidLoad
    {
        graphview.test = @"dd";
    }
    

    【讨论】:

      【解决方案2】:

      不设置框架,drawRect不会被调用。

      BPGraphView * graphview=[[BPGraphView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
      graphview.test = @"something";
      [self.view addSubview:graphview];
      

      【讨论】:

        【解决方案3】:

        我试过了,效果很好,在你的代码中,drawRect没有被调用

         BPGraphView * graphview=[[BPGraphView alloc] init];
            graphview.test = @"dd";
            [graphview drawRect:CGRectMake(0, 0, 0, 0)];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-31
          • 2019-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多