私はこれに数日間取り組んできました-モデルの1つから(コントローラーを介して)データをグラフ化するビューに取得することになっているカスタムプロトコルがあります。
これが私がこれを行う方法です-ステップバイステップ:
グラフ表示では、プロトコルを次のように宣言します。
@class GraphView;
@protocol GraphViewDataSource <NSObject>
-(CGFloat)yValueForGraphView:(GraphView *)sender usingXval:(CGFloat)xVal;
@end
次に、view.hでプロパティを宣言します
@interface GraphView : UIView
@property (nonatomic, weak) IBOutlet id <GraphViewDataSource> dataSource;
@end
view.mでプロパティを合成します。
@synthesize dataSource=_dataSource;
次に、drawRectで、このメソッドを呼び出して、別のコントローラーのモデルからCGFloatを戻します。
-(void) drawRect:(CGRect)rect
{
//context stuff, setting line width, etc
CGPoint startPoint=CGPointMake(5.0, 6.0);
NSLog(@"first, y value is: %f", startPoint.y);
startPoint.y=[self.dataSource yValueForGraphView:self usingXval:startPoint.x]; //accessing delegate via property
NSLog(@"now the y value now is: %f", startPoint.y);
//other code..
}
もう1つのViewControllerで、view.hファイルをインポートし、プロトコルに準拠していることを宣言しています。
#import "GraphView.h"
@interface CalculatorViewController () <GraphViewDataSource>
GraphViewのプロパティを作成する:
@property (nonatomic, strong) GraphView *theGraphView;
合成:
@synthesize theGraphView=_theGraphView;
セッターで、現在のコントローラーをdataSource(別名デリゲート)として設定します。
-(void) setTheGraphView:(GraphView *)theGraphView
{
_theGraphView=theGraphView;
self.theGraphView.dataSource=self;
}
また、prepareForSegue(修正を探しているときに試したものの1つ)でコントローラーをデリゲートとして設定しました。
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"GraphViewController"])
{
self.theGraphView.dataSource=self;
}
}
最後に、必要なメソッドを実装します。
-(CGFloat)yValueForGraphView:(GraphView *)sender usingXval:(CGFloat)xVal
{
CGFloat test=51.40; //just to test
return test;
}
そして、graphViewのdrawRectのテストNSLogから得られる出力は次のとおりです。
2012-10-25 20:56:36.352 ..[2494:c07] first, y value is: 6.000000
2012-10-25 20:56:36.354 ..[2494:c07] now the y value now is: 0.000000
これは、dataSourceを介して51.40を返すはずですが、そうではありません。理由がわからない!私を夢中にさせて、私はすべてを正しくやったようです。しかし、デリゲートメソッドは呼び出されていません。
私が見逃している愚かなことはありますか?
追加情報-コントローラーとGraphViewの図: