ios - 将参数传递给 Swift 3 中的 UIView 子类

标签 ios swift uiview subclass

我正在尝试将参数传递给 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/

相关文章:

ios - 为什么 self.view.subviews 在 vi​​ewDidLoad 中是一个空数组?

ios - 返回具有不同单元格标识符的单元格

swift - 在 Vapor 中的哪里创建自己的文件?

objective-c - UIViewController 未调用 viewDidLoad 且未创建 UIView 导致崩溃

iphone - 从 subview 中删除所有 UIButton

ios - 单击 UICollectionView 中的自定义单元格时如何触发 segue

objective-c - iOS -> setNavigationBarHidden 延迟

json - iOS - 快速下载 json

ios - 从特定行设置动态自定义单元格

ios - 为什么使用自动布局时需要调用layoutIfNeeded