【问题标题】:nib property is nil after is has been assigned - swift分配 is 后 nib 属性为 nil - swift
【发布时间】:2017-01-30 20:47:45
【问题描述】:

我有一个 UIView,我想将它加载到另一个 ViewController 中。在我的 VC 的 viewDidLoad 中,我加载了我的 UIView,它是 ContactUs,它工作正常。

var nib : ContactUs!
nib = ContactUs()
nib.tag = 100
nib.delegate = self
nib = Bundle.main.loadNibNamed("ContactUs", owner: nib, options: nil)?[0] as! ContactUs
nib.frame = CGRect(x: 0, y: 150, width: self.view.bounds.width , height: 120)
self.view.addSubview(nib)

因为我希望我的 UIView 可以重复使用,所以我这样编写了我的 ContactUs 类:

protocol ContactUsDelegate {
    func closeWindow()
}

class ContactUs: UIView {

    var delegate : ContactUsDelegate!

    @IBOutlet weak var cancel: UIButton!
    @IBAction func cancelAction(_ sender: Any) {
    if delegate != nil
    {
        delegate.closeWindow()
    }
    else
    {
        print("are you kidding me!")
    }
}
}

在我的 VC 中,我将 ContactUsDelegate 添加到类中并将这个函数放入其中:

func closeWindow()
{
    print("here we are!")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

视图加载正确,但是当我按下取消按钮时,它会打印“你在开玩笑吗!”这意味着 delegatenull 。为什么当我说它是 self 时,delegate 说它是 nil?

【问题讨论】:

    标签: ios uiview


    【解决方案1】:

    nib = Bundle.main.loadNibNamed("ContactUs", owner: nib, options: nil)?[0] as! ContactUs

    返回一个新的“ContactUs”视图实体。尝试在此行之后设置委托。

    你的代码应该是:

    var nib : ContactUs!
    nib = Bundle.main.loadNibNamed("ContactUs", owner: nib, options: nil)?[0] as! ContactUs
    nib.tag = 100
    nib.delegate = self
    nib.frame = CGRect(x: 0, y: 150, width:         self.view.bounds.width , height: 120)
    self.view.addSubview(nib)
    

    【讨论】:

      【解决方案2】:

      请试试这个

      var nib : ContactUs!
      nib = Bundle.main.loadNibNamed("ContactUs", owner: self, options: nil)?[0] as! ContactUs
      nib.tag = 100
      nib.delegate = self
      nib.frame = CGRect(x: 0, y: 150, width: self.view.bounds.width , height: 120)
      self.view.addSubview(nib)
      

      这是因为您在设置标签和删除后分配了一个新的 ContactUs 实例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-19
        • 2014-11-15
        • 1970-01-01
        • 2015-03-27
        • 2014-03-22
        • 2015-04-15
        • 1970-01-01
        相关资源
        最近更新 更多