我正在尝试将参数传递给 UIView 子类。 我的代码似乎可以工作,但初始化后所有参数都变成零:当在绘制函数中调用 lineWidth (参数之一)时,我遇到此错误:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
这是我的 viewController 代码:
import UIKit
class ViewController: UIViewController,UIGestureRecognizerDelegate,UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var matrixView = UIMatrixView(mat: [[Bool]](),gRows:20,gCols:20,lWidth:2)
override func viewDidLoad() {
super.viewDidLoad()
// scrollView.delegate = self
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.matrixView
}
}
这是针对 UIView 子类的:
import UIKit
class UIMatrixView: UIView {
var matrix : [[Bool]]!
var gridRows : Int!
var gridCols : Int!
var lineWidth : Int!
init(mat: [[Bool]], gRows : Int, gCols : Int, lWidth : Int){
print("here")
self.matrix=mat
self.gridRows=gRows
self.gridCols=gCols
self.lineWidth=lWidth
super.init(frame: CGRect())
print(lineWidth)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
print(lineWidth)
}
}
最佳答案
自定义 UIView 标记为弱属性。
在代码中创建后,不会保留对其的强引用。
可以在 Storyboard 中设置标有 IBOutlet 的属性。
否则,添加后将弱引用设置为 subview (addSubview
):
func appendMatrixView() {
let mView = MatrixView(...
//Important lines.....
addSubview(mView)
self.matrixView = mView;
}
关于ios - 将参数传递给 Swift 3 中的 UIView 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41525801/