2015-07-04 31 views
1

我在我的Draw2D类中附加了视图控制器中的视图中的以下代码。在Swift中调用Draw函数

在视图控制器中,我有一个var Drawing = Draw2D()。我有一个按钮连接到self.Drawing.Check()执行功能“检查”。问题是我无法获得屏幕上的线。椭圆工作正常,功能检查表现良好,我可以看到println()。 有什么不对?

import UIKit 

class Draw2D: UIView { 

    override func drawRect(rect: CGRect) { 
     let context = UIGraphicsGetCurrentContext() 
     CGContextSetLineWidth(context, 4.0) 
     CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) 
     let rectangle = CGRectMake(60,170,200,80) 
     CGContextAddEllipseInRect(context, rectangle) 
     CGContextStrokePath(context) 
    } 

    func Check() { 
     let context = UIGraphicsGetCurrentContext() 
     CGContextSetLineWidth(context, 2.0) 
     CGContextMoveToPoint(context, CGFloat(100), CGFloat(300)) 
     CGContextAddLineToPoint(context, CGFloat(100 + 200), CGFloat(300 + 100)) 
     CGContextStrokePath(context) 
    } 
} 
+0

哪里是'检查()'叫什么名字? – luk2302

+0

这是的ViewController – user2761551

+0

'变种绘图= Draw2D的() @IBAction FUNC Button1的(发送者:AnyObject) { self.Drawing.Check() }' – user2761551

回答

1

您对Check()通话是普通的渲染循环之外 - 我真的不知道是什么UIGraphicsGetCurrentContext()在这种情况下,实际上返回。我猜测它会返回nil

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current.

反正是不会改变的事实,你不能只是调用Check()并期望行被渲染。假设这一行实际上是呈现出来的:在下一次呈现迭代中,您将再次执行写在drawRect内部的内容,因此不会再显示该行。

你需要做的是在drawRect内部创建某种逻辑来确定是否需要调用Check()

一种可能的方式做这将是如下:

class Draw2D: UIView { 

    var callCheck:Bool? // changing it to Bool! or Bool will change the required check a few lines below 

    override func drawRect(rect: CGRect) { 
     let context = UIGraphicsGetCurrentContext() 
     CGContextSetLineWidth(context, 4.0) 
     CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) 
     let rectangle = CGRectMake(60,170,200,80) 
     CGContextAddEllipseInRect(context, rectangle) 
     CGContextStrokePath(context) 
     if callCheck != nil && callCheck! { 
      Check() 
     } 
    } 

    func Check() { 
     let context = UIGraphicsGetCurrentContext() 
     CGContextSetLineWidth(context, 2.0) 
     CGContextMoveToPoint(context, CGFloat(100), CGFloat(300)) 
     CGContextAddLineToPoint(context, CGFloat(100 + 200), CGFloat(300 + 100)) 
     CGContextStrokePath(context) 
    } 
} 

改变你IBAction

@IBAction func Button1(sender: AnyObject) { 
    self.Drawing.callCheck = true 
    self.Drawing.setNeedsDisplay() 
} 
+0

嗨和thx如此。我真正想做的是在drawRect中描述一个设置,然后是一个func drawLine,它可以绘制所有的线,并且可以从其他函数中调用。我在哪里以及如何声明该drawLine函数? – user2761551

+0

顺便说一句,我无法获得建议的工作变更 – user2761551

+0

您可以在任何需要的地方声明它,您只需在将drawLine方法调用为'drawRect'时移动逻辑。所有绘制任何东西都必须直接或间接从'drawRect'调用 – luk2302

相关问题