2

所以我有一个主viewController视图,它有一个堆栈视图,我想向其中添加我创建的自定义视图的多个实例。

所以我的想法是创建一个继承自UIView. 我希望视图始终为 40x40,所以我创建了一个新的 init 来处理这个问题?(不确定这是否正确):

class QuickAddView: UIView {

    @IBOutlet weak var iconLabel: UILabel!

    var task: Task = Task()

    public init(task: Task) {
        self.task = task
        super.init(frame: CGRect(x: 0, y: 0, width: 40, height: 40))

        configureView()
    }

    private func configureView() {
        self.layer.cornerRadius = self.frame.size.width / 2
        self.backgroundColor = task.color

        configureViewElements()
    }

    private func configureViewElements() {
        configureIconLabel()
    }

    private func configureIconLabel() {
        // CRASH: - iconLabel is nil here
        self.iconLabel.text = task.icon
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}

然后我有一个 QuickAddView 笔尖,将其自定义类设置为 QuickAddView.swift

最后,我在我的viewController

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    configureViewElements()
}

private func configureViewElements() {
    configureQuickAddStackView()
}

private func configureQuickAddStackView() {
    let quickAddView = QuickAddView(task: Task(name: "Go to the store", icon: "", color: .purple))

    quickAddStackView.addArrangedSubview(quickAddView)
}

我遇到的问题iconLabelnil当我尝试设置我的QuickAddView. 我也不知道我是否正在做这个创建自定义视图的过程是否正确。

4

2 回答 2

1

由于您要从 xibFile 连接 IBOutlet,因此您必须使用

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
    configureView()
}

同样在你的课堂上,你必须用它来实例化它

if let quickAddView  = Bundle.mainBundle().loadNibNamed("QuickAddView", owner: self, options: nil).first as? QuickAddView {
 quickAddView.task = task
 }
于 2018-06-28T04:25:38.943 回答
-1

问题是您正在代码中创建自定义视图,但使用 IBOutlet 作为 iconLabel。IBOutlet 用于您在 Interface Builder 中构建的东西,而不是在代码中。如果要在代码中创建 QuickAddView,还需要在代码中的 QuickAddView 类中创建 iconLabel。您需要进行以下修改:

weak var iconLabel: UILabel?

private func configureIconLabel() {
    iconLabel = UILabel(frame: CGRect())
    if let iconLabel = iconLabel {
        iconLabel.text = task.icon
        addSubview(iconLabel)
    }
}

请注意,我传入了一个归零的 CGRect,但您需要使用任何您想要的 UILabel 原点和大小,或者使用自动布局来配置 iconLabel 的显示位置。

于 2018-06-28T04:32:36.703 回答