Mitchell Ingram
Mitchell Ingram

Reputation: 706

Using UIView function from other class causes crashes

I am sure this has been asked a million times. But my search kept coming up with objective C solutions.

I am calling a UIViewController class from a different class. I would like it to update the screen. When the function is called from the ViewController, it works fine. But when it is called from another class, it crashes on:

tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))

Saying that the unwrapped optional returned nil. tempImageView is an outlet of an UIImageView in the UIViewController. I guess I am not clear on how outside class function calls really work. Does anyone know the solution for this?

EDIT:

class ViewController: UIViewController, NSURLSessionDelegate {
var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false
var xArray = [CGFloat]()
var yArray = [CGFloat]()
var scale: CGFloat = 0.0
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var tempImageView: UIImageView!
......
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {

    // 1
    UIGraphicsBeginImageContext(self.view.frame.size)
    let context = UIGraphicsGetCurrentContext()
    tempImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))

    // 2
    CGContextMoveToPoint(context, fromPoint.x, fromPoint.y)
    CGContextAddLineToPoint(context, toPoint.x, toPoint.y)

    // 3
    CGContextSetLineCap(context, .Round)
    CGContextSetLineWidth(context, brushWidth)
    CGContextSetRGBStrokeColor(context, red, green, blue, 1.0)
    CGContextSetBlendMode(context, .Normal)

    // 4
    CGContextStrokePath(context)

    // 5
    self.tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    self.tempImageView.alpha = opacity
    UIGraphicsEndImageContext()

}

And the call from the other controller

func getChatMessage() {
    socket.on("browser") { (dataArray, socketAck) -> Void in
        for _ in dataArray {
       ViewController().drawLineFrom(CGPoint(x: 0,y: 0), toPoint: CGPoint(x: 1,y: 1))
        }
    }
}

Upvotes: 0

Views: 42

Answers (1)

GetSwifty
GetSwifty

Reputation: 7756

You're initializing a new ViewController and trying to do something with it immediately. This won't work for a number of reasons that show you are probably a beginner. (welcome!) You either need to review how UIViewControllers work, (specifically the lifecycle), or review how objects work :)

Upvotes: 1

Related Questions