我开始学习Xcode,当我按下按钮时,我不明白如何在视图中画一条线我有这个代码
- (void)drawRect:(CGRect)rect
{
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(con, 5);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGFloat componen [] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(space, componen);
CGContextSetStrokeColorWithColor(con, color);
CGContextMoveToPoint(con, 0, 0);
CGContextAddLineToPoint(con, 100, 100);
CGContextStrokePath(con);
CGColorSpaceRelease(space);
CGColorRelease(color);
}
这段代码在我启动应用程序时画了一条线,但我想在使用参数 (x1,x2,y1,y2) 按下按钮时启动这段代码。我创建了一个这样的函数
- (void)drawLine
{
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(con, 5);
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGFloat componen [] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(space, componen);
CGContextSetStrokeColorWithColor(con, color);
CGContextMoveToPoint(con, x1, y1);
CGContextAddLineToPoint(con, x2, y2);
CGContextStrokePath(con);
CGColorSpaceRelease(space);
CGColorRelease(color);
}
但它不会画
怎么做?
定义你的drawRect:
,以便它决定是否应该画一条线:
- (void)drawRect:(CGRect)rect {
if (self.drawLine) {
[self drawLineWithContext: UIGraphicsGetCurrentContext()];
self.drawLine = NO;
}
}
点击按钮后,让视图控制器设置视图参数并告诉系统刷新视图:
- (IBAction)doDrawing:(id)sender {
self.drawView.drawLine = YES;
self.drawView.x1 = 20.0;
self.drawView.x2 = 200.0;
self.drawView.y1 = 10.0;
self.drawView.y2 = 350.0;
[self.drawView setNeedsDisplay];
}
我为 UIView 添加一行非常简单。
UILabel *line = [[UILabel alloc]init];
line.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
line.frame = CGRectMake(0, 0, 320, 1);
[self.view addSubview:line];
然后您可以按按钮来控制其可见属性。
你的问题可以吗?
- (void)drawRect:(CGRect)rect { }
系统调用的方法。在视图加载之前,系统将调用它并绘制内容。
因此,如果在视图加载后更改绘图内容,则必须要求系统调用drawRect方法。 因此,您必须调用相关视图的setNeedsDisplay方法。
[我的视图集需求显示];
感谢