简体   繁体   English

在Swift 3中将参数传递给UIView子类

[英]Pass arguments to UIView subclass in Swift 3

I'm trying to pass argument to a UIView subclass. 我试图将参数传递给UIView子类。 My code seems to work but after initialization the all the argument become nil: when lineWidth (one of the argument) is called in the draw function I've this error: 我的代码似乎可以工作,但是初始化后所有参数都变为nil:在draw函数中调用lineWidth(参数之一)时,我遇到了以下错误:

"fatal error: unexpectedly found nil while unwrapping an Optional value" “致命错误:解开可选值时意外发现nil”

This is my code for the viewController: 这是我的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
    }
}

And this is for the UIView subclass: 这是针对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)
    }
}

The custom UIView marked as a weak property. 自定义UIView标记为弱属性。

Strong Reference on it is not keep after creation in the code. 创建代码后,不保留对此的强引用。

Property which is marked with IBOutlet can be set in Storyboard. 可以在情节提要中设置带有IBOutlet标记的属性。

Or otherwise, set weak reference after addition as subview ( addSubview ) : 否则,将添加后的弱引用设置为subview( addSubview ):

func appendMatrixView() {
  let mView = MatrixView(...
 //Important lines.....
   addSubview(mView)
   self.matrixView = mView; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM