UILabel作为UIView子类的一部分不会启动

时间:2019-02-11 21:43:13

标签: ios swift uilabel custom-controls

因此,我有一个UIView的子类,我想包含两个自定义UILabel。我的UIView的子类初始化为“应该”,但是UILabel却没有(我也尝试过使用普通的UILabels,但这也不起作用)。没有任何打印语句的痕迹,并且不会显示它们。当我直接将它们放在情节提要上时,它们就可以正常工作。

我不知道要转身,也不是哪里出了问题。我已经搜寻互联网好几天了。请帮助这位初学者...

class MainscreenButton: UIView {

 @IBOutlet var icon: LAUILabel!
 @IBOutlet var info: LAUILabel!

 required init(coder aDecoder: NSCoder){
     super.init(coder: aDecoder)!
     print("mainscreenbutton requiredinit")
 }

 override init(frame: CGRect) {
     super.init(frame: frame)
     print("mainscreenbutton frameinit")
 }
}

2 个答案:

答案 0 :(得分:0)

好吧。

它们应该初始化..您只需要给它们一个框架/边界/位置。 IBOutlet暗示情节提要或NIB,因此请确保在情节提要或笔尖中设置类并连接IBOutlet。然后给标签加上约束+文字,它们应该出现。

如果您想做类似var icon = LAUILabel()的事情,然后在初始化程序中也做类似icon.frame = CGRect(... blah whatever)或自动布局的编程约束,那么它们也应该起作用

请注意,尽管我将其作为情节提要/笔尖初始化程序,但在我的代码中

required init?(coder aDecoder: NSCoder) {

}

不确定是否只是略微不同的方法签名而已

如果您没有给他们明确的宽度限制(也许您只给它一个x),您还需要调用label.layoutIfNeeded()。因为如果没有文本,没有宽度或没有前导/尾随x约束,它将使用0宽度进行初始化。

答案 1 :(得分:0)

我不确定您为什么将UIView做为按钮,但是如果您想这样做,请按以下步骤操作:

1)创建UILabel自定义类

class LAUILabel: UILabel {

    //you can even define some params like @IBOutlet images ...

    override init(frame: CGRect) {
        super.init(frame: frame)
        updateUI()
    }

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

    private func updateUI() {
        backgroundColor = .red
        textColor = .green
        numberOfLines = 1
        textAlignment = .center
    }

}

2)创建您的MainscreenButton

class MainscreenButton: UIView {

 @IBOutlet weak var icon: LAUILabel!
 @IBOutlet weak var info: LAUILabel!

 required init(coder aDecoder: NSCoder){
     super.init(coder: aDecoder)!
     print("mainscreenbutton requiredinit")
 }

 override init(frame: CGRect) {
     super.init(frame: frame)
     print("mainscreenbutton frameinit")
 }
}

3)将您的UI与自定义类连接 您将转到情节提要或Xib文件,然后将视图拖到Identity Inspector,然后在自定义类中插入类“ MainscreenButton”的名称,然后将UILabels拖动到该视图内,并像在“ LAUILabel之前”一样从身份检查器中更改自定义类'然后将标签与应该响应的corespondent UI链接。

4)否则,您可以创建没有情节提要的标签,如下所示:

class MainscreenView: UIView {

    required init(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)!
        print("mainscreenbutton requiredinit")

        let icon = LAUILabel(frame: CGRect(origin: CGPoint(x: 100, y: 50), size: CGSize.zero))
        icon.text = "icon"
        icon.sizeToFit()
        addSubview(icon)

        let info = LAUILabel(frame:  CGRect(origin: CGPoint(x: 200, y: 50), size: CGSize.zero))
        info.text = "info"
        info.sizeToFit()
        addSubview(info)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        print("mainscreenbutton frameinit")

    }

}