2016-08-17 68 views
0

我相信這已被問了一百萬次。但我的搜索不斷提出客觀的C解決方案。使用UIView函數從其他類導致崩潰

我從另一個類調用一個UIViewController類。我希望它能更新屏幕。當從ViewController調用該函數時,它可以正常工作。但是當它被另一個類調用時,它會崩潰:

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

說出解包的可選返回nil。 tempImageView是UIViewController中UIImageView的出口。我想我不清楚外部類函數調用是如何工作的。有誰知道這個解決方案?

編輯:

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() 

} 

而從另一個控制器

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)) 
     } 
    } 
} 
+0

顯示代碼創建您調用方法的視圖控制器的代碼。 – dan

+0

增加了功能。 –

+0

你需要做什麼,即「我希望它更新屏幕」是什麼意思?你想轉移到'ViewController'嗎?在你的'getChatMessage'函數中,你創建了一個新的'ViewController'實例,並立即在這個新實例上調用你的方法。這是行不通的,因爲即使它沒有崩潰,你的結果也不可見。 – Losiowaty

回答

1

你初始化一個新ViewController並試圖立即用它做什麼呼叫。這不會有很多原因表明你可能是初學者。 (歡迎!)您或者需要查看UIViewControllers的工作方式(特別是生命週期),或者查看對象的工作方式:)

+0

OP沒有進攻,但我會說如果他們都做到了,我會是最好的。 – Losiowaty

+0

可能...不想承擔太多,雖然:) – PeejWeej

+0

據我所知,初始化它是錯誤的,但我嘗試了一個共享var視圖,也失敗了。從控制器外部使用視圖只是沒有很好的文檔。必須有一個簡單的方法來做到這一點。 –