我按照一个教程创建了一个图表。这是Part 3 tutorial,但是我运行图表时没有显示。这是我的代码:
Gridview.h
#import <UIKit/UIKit.h>
#define kGraphHeight 300
#define kDefaultGraphWidth 900
#define kOffsetX 0
#define kStepX 50
#define kGraphBottom 300
#define kGraphTop 0
#define kStepY 50
#define kOffsetY 10
@interface GridView : UIView
@end
**GridView.m**
#import "GridView.h"
@implementation GridView
- (void)drawLineGraphWithContext:(CGContextRef)ctx
{
//float data[] = {0.7, 0.4, 0.9, 1.0, 0.2, 0.85, 0.11, 0.75, 0.53, 0.44, 0.88, 0.77, 0.99, 0.55};
float data[] = {0.7, 0.4, 0.9, 1.0, 0.2, 0.85, 0.11, 0.75, 0.53, 0.44, 0.88, 0.77, 0.99, 0.55};
CGContextSetLineWidth(ctx, 2.0);
CGContextSetStrokeColorWithColor(ctx, [[UIColor colorWithRed:1.0 green:0.5 blue:0 alpha:1.0] CGColor]);
int maxGraphHeight = kGraphHeight - kOffsetY;
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, kOffsetX, kGraphHeight - maxGraphHeight * data[0]);
for (int i = 1; i < sizeof(data); i++)
{
CGContextAddLineToPoint(ctx, kOffsetX + i * kStepX, kGraphHeight - maxGraphHeight * data[i]);
}
CGContextDrawPath(ctx, kCGPathStroke);
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
[self drawLineGraphWithContext:context];
// Draw the background image
UIImage *image = [UIImage imageNamed:@"background.png"];
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextDrawImage(context, imageRect, image.CGImage);
CGContextSetLineWidth(context, 0.6);
CGContextSetStrokeColorWithColor(context, [[UIColor lightGrayColor] CGColor]);
CGFloat dash[] = {2.0, 2.0};
CGContextSetLineDash(context, 0.0, dash, 2);
// How many lines?
int howMany = (kDefaultGraphWidth - kOffsetX) / kStepX;
// Here the lines go
for (int i = 0; i <= howMany; i++)
{
CGContextMoveToPoint(context, kOffsetX + i * kStepX, kGraphTop);
CGContextAddLineToPoint(context, kOffsetX + i * kStepX, kGraphBottom);
}
int howManyHorizontal = (kGraphBottom - kGraphTop - kOffsetY) / kStepY;
for (int i = 0; i <= howManyHorizontal; i++)
{
CGContextMoveToPoint(context, kOffsetX, kGraphBottom - kOffsetY - i * kStepY);
CGContextAddLineToPoint(context, kDefaultGraphWidth, kGraphBottom - kOffsetY - i * kStepY);
}
CGContextStrokePath(context);
CGContextSetLineDash(context, 0, NULL, 0); // Remove the dash
}
viewcontroller.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
UIScrollView *scroller;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end
viewcontroller.m
#import "ViewController.h"
#import "GridView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
scroller.contentSize = CGSizeMake(kDefaultGraphWidth, kGraphHeight);
}
为什么我无法生成要显示的图表。请帮我解决。感谢
答案 0 :(得分:0)
尝试在view controller.m中添加此方法
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
GridView *gv=[GridView alloc]initWithFrame:CGRectMake(0,0,100,100)];
[ self.view addSubView:gv];
}