自定义视图的IBOutlet为零

时间:2018-06-28 02:13:51

标签: swift uiview uiviewcontroller xib

因此,我有一个主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)
}

我遇到的问题是,当我尝试设置iconLabel时,我的nilQuickAddView。我也不知道我是否正在执行创建自定义视图的过程。

2 个答案:

答案 0 :(得分: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
 }

答案 1 :(得分:0)

问题是您正在代码中创建自定义视图,但对iconLabel使用IBOutlet。 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,但是您将要使用UILabels的原点和大小,或者使用自动布局来配置iconLabel的显示位置。