Swift XIB设置标签文本

时间:2019-02-01 14:52:11

标签: swift xcode

我正在尝试创建一个“警报横幅”,以在警报横幅内的标签中显示图钉。

我正在通过“ ViewController.swift”调用警报横幅,

AlertBanner().Show(self, pin: 2520)
  

致命错误:在隐式展开一个   可选值

该错误告诉我AlertBannerText标签为nil。我怀疑它还没有创建,但是在填充它之前我该如何等待标签存在?

AlertBanner类中的任何代码:

class AlertBanner : UIView {

    @IBOutlet var AlertBannerText: UILabel!

    static weak var delegate: AlertBannerDelegate!

     func Show(_ vc: ViewController, pin: Int){

        var onlineBanner: UIView?
        var topPadding: CGFloat?
        var menuView: UIView?


      AlertBannerText.text = "\(pin)"

       let window = UIApplication.shared.keyWindow!
        if let menu = vc.view.viewWithTag(3) { menuView = menu}

        onlineBanner = UINib(nibName: "AlertBanner", bundle: nil).instantiate(withOwner: nil, options: nil).first as? AlertBanner

        if #available(iOS 11.0, *) { topPadding = window.safeAreaInsets.top }

        onlineBanner?.frame.origin.y = 0 - (window.frame.size.width / 7.5 + topPadding!)
        onlineBanner!.frame.size.width = window.frame.size.width
        onlineBanner!.frame.size.height = window.frame.size.width / 5
        onlineBanner!.tag = 2
        vc.view.insertSubview(onlineBanner!, belowSubview: menuView!)

        if let banner = vc.view.viewWithTag(2) {
            UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
                banner.frame.origin.y = window.frame.size.width / 7.5 + topPadding!

            }, completion: nil)
        }


    }

1 个答案:

答案 0 :(得分:0)

这样做

AlertBanner().//////

创建一个没有布局的实例,因此所有出口均为nil,您需要使用以下内容创建一个实例

class func getInstance() -> AlertBanner {

  let onlineBanner = UINib(nibName: "AlertBanner", bundle: nil).instantiate(withOwner: nil, options: nil).first as! AlertBanner
  return onlineBanner 
}

然后

 AlertBanner.getInstance().//////