您必须为图科文类设定一个财产,如:
@interface GraphView : UIView
@property float endXPoint;
接着,从主计长的角度,你将图表显示的“意见”变量定为:
[myGraphView setendXPoint: [mySlider value]];
[myGraphView setNeedsDisplay];
The last line ask GraphView to update the View, calling the drawRect method.
In the drawRect method you can use endXPoint directly because it is a class property.
这是正确的版本:
//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