![](/img/trans.png)
[英]“Unexpectedly found nil while implicitly unwrapping an Optional value” on overrided init in custom UIView class
[英]'unexpected nil while wrapping optional value' when passing data from my viewcontroller class to my custom class UIView placed in the same scene
我創建了一個自定義類UIView,以便可以從viewController類中獲取圖像的一部分。 我在viewController類中創建了要放大的UIView,並將其@IBOutlet屬性命名為xRaySuperView:UIView! 我使用情節提要板在此視圖中嵌入了放大鏡:UIView自定義類視圖。
然后,我在自定義Magnifier類中實例化了一個viewController對象。 但是,當我嘗試轉換xRaySuperView的層並在上下文中對其進行渲染時,構建將失敗並指出“在展開可選值時出現意外的nil”。
看來我的xRaySuperView沒有將圖層值傳遞給Magnifier類。 (它是th
這是在構建期間創建錯誤的最后一行。
import UIKit
import QuartzCore
class MagnifierView: UIView {
var viewController: ViewController!
// First Step: Initialize the UIView
required init?(coder aDecoder: NSCoder) {
// Create instance of ViewController Class
let viewController = ViewController()
super.init(coder: aDecoder)
// Makes the circle-shape outline.
self.layer.borderColor = UIColor.blue.cgColor
self.layer.borderWidth = 4
self.layer.cornerRadius = 65 //1/2 the width of the frame
self.layer.masksToBounds = true
}
// Perform transforms on the xray view
override func draw(_ rect: CGRect) {
let xrayContext = UIGraphicsGetCurrentContext()
xrayContext?.translateBy(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
xrayContext?.scaleBy(x: 1.5, y: 1.5)
self.viewController.xRaySuperView.layer.render(in: xrayContext!)
}
}
當您使用ViewController()
,您只是在創建一個對象,而不是填寫其出口(除非您在ViewController
有init
代碼可以這樣做)。 您要么需要從情節提要或.xib文件中實例化ViewController
,要么(更可能是)將現有實例傳遞給此類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.