本文介绍了目标 C - 将值从 UIViewController 传递给 UIView - 我一直为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,让我说我是 Objective C 的新手.

First of all, let me say that I am new to Objective C.

我基本上是试图将 originalPriceOnGraph 变量从 ViewController (UIViewController) 传递到 GraphView (UIView) 的原始变量.但是,当我尝试显示原件时,我一直得到 0.00.我不明白到底是什么问题.这是我的一些代码:

I'm basically trying to pass the originalPriceOnGraph variable from ViewController (UIViewController) to the original variable from GraphView (UIView). However, I keep getting 0.00 when I try and display original. I don't get what exactly is the problem. Here's some of my code:

GraphView.h

GraphView.h

@interface GraphView : UIView
@property (nonatomic) double original;
@end

GraphView.m

GraphView.m

@implementation GraphView
@synthesize original;

- (id)initWithFrame:(CGRect)frame
{
   //some code here
}
- (void)drawRect:(CGRect)rect;
{
   NSLog(@"%.2f", original);
   //some more code here
}
@end

ViewController.m

ViewController.m

@interface OtherViewController ()
@end
@implementation OtherViewController
@synthesize originalPriceOnGraph;
@synthesize graph;

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view.

   originalPriceOnGraph = 20.00;

   graph = [[GraphView alloc] init];
   graph.original = originalPriceOnGraph;
}

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

视图控制器.h

@interface OtherViewController : UIViewController
@property (strong, nonatomic) GraphView *graph;
@property (nonatomic) double originalPriceOnGraph;
@end

先谢谢你!

我能够通过在 OtherViewController 和 GraphView 之间创建一个 IBOutlet 来解决这个问题.我还去掉了 ViewController.m 中 GraphView 的 alloc init 语句.谢谢大家的建议!

I was able to solve this by creating an IBOutlet between the OtherViewController and GraphView. I also got rid of the alloc init statement for GraphView in ViewController.m. Thank you all for your suggestions!

推荐答案

您确定 GraphView 的 drawRect: 方法在您设置其原始"属性之前没有被调用?

Are you sure the GraphView's drawRect: method isn't getting called before you set its 'original' property?

如果是这样,请尝试使用 original 的默认值初始化 GraphView 的任何实例.

If so, try initializing any instance of a GraphView with a default value for original.

在 GraphView.h 中:

In GraphView.h:

-(id)initWithOriginal:(double)original;

在 GraphView.m 中:

In GraphView.m:

-(id)initWithOriginal:(double)original
{
    self = [super init];
    if (self) {
        [self setOriginal:original];
    }
    return self;
}

在 ViewController.m 中:

In ViewController.m:

-(void)viewDidLoad
{
    [super viewDidLoad];

    originalPriceOnGraph = 20.00;

    [self setGraph:[[GraphView alloc] initWithOriginal:originalPriceOnGraph]];
}

这篇关于目标 C - 将值从 UIViewController 传递给 UIView - 我一直为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 00:44