OGeek|极客世界-中国程序员成长平台

标题: ios - 从 subview 中的父 View Controller 检索数组 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:55
标题: ios - 从 subview 中的父 View Controller 检索数组

所以过去几天我似乎一直在尝试为此寻找各种解决方案,并决定最好还是问问别人。 我正在使用 Storyboard ,我将一个数组从一个 ViewController 发送到另一个就好了。但是一旦在这个 SecondViewController 我遇到了问题。然后,我希望能够访问此 View Controller 的 subview 中的数组,以便能够使用数据绘制图表,但是每当我尝试时,我总是从 subview 中的代码中获取 null,即使它肯定在 ParentViewController 中.有人可以看看我当前的代码,让我知道如何在我的 subview 中获取这些数据。

ParentViewController.h

#import <UIKit/UIKit.h>
#import "GraphView.h"
#import "Model.h"
@interface GraphViewController : UIViewController
 @property (strong) Model *model;
 @property (weak) GraphView *graph;
 @property (strong) NSArray *data;
@end

ParentViewController.m

#import "GraphViewController.h"

@interface GraphViewController ()

@end

@implementation GraphViewController
@synthesize graph;
- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view.
    NSLog(@"Model data: %@",self.data);//prints just fine
[self.graph setNeedsDisplay];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

SubView.h

 #import <UIKit/UIKit.h>
 #import "Model.h"
 @interface GraphView : UIView 
 @property (weak) NSArray *array;
 @property (strong) Model *model;
 @end

Subview.m

 #import "GraphView.h"
 #import "GraphViewController.h"
 @implementation GraphView
- (id)initWithFrameCGRect)frame dataArrayNSArray*)data {
   self = [super initWithFrame:frame];
   if (self) {
    // Initialization code
    }
return self;
 }
- (void)drawRectCGRect)rect {
   // Drawing code
    NSLog(@"Draw Rect");
    NSLog(@"%@", self.array);//The bit that keeps returning null
    if (self.array != nil){
       NSLog(@"Drawing Rect");
       CGContextRef ctx = UIGraphicsGetCurrentContext();
       CGContextBeginPath(ctx);
       CGContextMoveToPoint(ctx, 160, 100);
       CGContextAddLineToPoint(ctx,260,300);
       CGContextAddLineToPoint(ctx,60,300);
       CGContextClosePath(ctx);
       [[UIColor blueColor] setFill];
       [[UIColor greenColor] setStroke];
       CGContextSetLineWidth(ctx,2.0);
       CGContextDrawPath(ctx,kCGPathFillStroke);
    }

 }

现在我知道它现在会返回 null,因为我实际上并没有将它分配给任何东西,但是我尝试了很多不同的方法来尝试将它分配给父 View Controller 中的数据数组,我忘记了如何我什至开始了。任何帮助将不胜感激!



Best Answer-推荐答案


viewDidLoad 中分配 GraphView 的数据。还要确保您的 self.graph 已正确连接/初始化。

- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view.
   NSLog(@"Model data: %@",self.data);//prints just fine
   self.graph.array = self.data;
   [self.graph setNeedsDisplay];
}

关于ios - 从 subview 中的父 View Controller 检索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237413/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4