0

我正在尝试绘制一个根据滑块的值上下移动的图形。我的图表是在属于自定义类 GraphView 的视图中绘制的。项目有一个 ViewController,滑块调用方法 moveLine。这有一个属性 endXPoint 我已经设置为: endXPoint = mySlider.value

我的问题是我不知道如何从我的 GraphView 的 drawRect 方法中引用这个值。

我尝试在 ViewController 中创建对 GraphView 的引用并在那里设置属性,但它不起作用:
GraphView *myGraphView = (GraphView *)self.view;
myGraphView.endXPoint = mySlider.value;

4

1 回答 1

0

您必须像这样为 GraphView 类设置一个属性:

@interface GraphView : UIView
@property float endXPoint;

然后从 ViewController 中设置 GraphView 变量,如:

[myGraphView setendXPoint: [mySlider value]];
[myGraphView setNeedsDisplay];

最后一行要求 GraphView 更新 View,调用 drawRect 方法。在 drawRect 方法中,您可以直接使用 endXPoint,因为它是一个类属性。

这是正确的版本:

//ViewController.h

#import <UIKit/UIKit.h> 
#import "GraphView.h" //import headers in the header file

@interface ViewController : UIViewController  

@property (strong, nonatomic) IBOutlet UISlider *mySlider;  
@property (strong, nonatomic) IBOutlet UILabel *myLabel;  
@property (strong, nonatomic) IBOutlet GraphView *myGraphView; //Connect this with the IB

- (IBAction)moveLine:(id)sender; 
- (IBAction)setLabelText:(id)sender;  
@end  

//ViewController.m

#import "ViewController.h"   

@implementation ViewController  
@synthesize mySlider;  
@synthesize myLabel;  
@synthesize myGraphView;



- (IBAction)moveLine:(id)sender {  
    [myGraphView setendXPoint:[mySlider value]];  
    [myGraphView setNeedsDisplay];  
}  

@end 

//GraphView.h 

#import <UIKit/UIKit.h>  

@interface GraphView : UIView  
@property float endXPoint;  


@end

//GraphView.m  

#import "GraphView.h"   

@implementation GraphView  
@synthesize endXPoint;  


- (void)drawRect:(CGRect)rect  
{

    CGContextRef ctx = UIGraphicsGetCurrentContext(); //get the graphics context  
    CGContextSetRGBStrokeColor(ctx, 1.0, 0, 0, 1);   
    CGContextMoveToPoint(ctx, 0, 0);  
    //add a line from 0,0 to the point 100,100;   
    CGContextAddLineToPoint( ctx, endXPoint,100);  
    //"stroke" the path  
    CGContextStrokePath(ctx);  
}  


@end
于 2012-04-30T09:52:22.487 回答