我是初学者。我只是想在不使用IB的情况下绘制一条简单的线条。 我用的代码是
lineViewController.m
-(id)init
{
if(self = [super init])
{
myView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,440)];
myView.backgroundColor = [UIColor grayColor];
mView = [[UIView alloc]initWithFrame:CGRectMake(0,0,200,200)];
self.view = myView;
[myView addSubView:mView];
}
return self;
}
-(void)viewWillAppear:(BOOL)animated
{
line = [[MyView alloc]init];
[line setNeedsDisplay];
}
MyView.m
#import "MyView.h"
@implementation MyView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(c, red);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 150.0f, 200.0f);
CGContextSetLineWidth(c, 5.0f);
CGContextAddLineToPoint(c, 50,300);
CGContextAddLineToPoint(c, 260,300);
CGContextClosePath(c);
}
但我无法画画。你能帮我么。 提前谢谢。
答案 0 :(得分:1)
viewWillAppear中的代码不执行任何操作,因为行永远不会添加到视图层次结构中。由于上述原因,MyView drawRect从未被调用,而“myView”被分配为UIView而不是MyView。尝试在视图控制器init中更改alloc。
myView = [[MyView alloc]initWithFrame:CGRectMake(0,0,320,440)];
此外,代码将按写入方式泄漏。留意保留&释放内存管理。