Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

swift - Crash on DidSet from external XIB

I have an external XIB that is @IBDesignable. Inside the view that shows this XIB, I have this outlet.

  @IBOutlet weak var digitizingButton: DigitizingButton! {
    didSet {
      digitizingButton.buttonIsBeingTouched = {[weak self] in
        // bla bla
      }
    }
  }

crash on

digitizingButton.buttonIsBeingTouched = {[weak self] in

EXC_BAD_ACCESS (code 2)

DigitizingButton loads like this:

 required init?(coder decoder: NSCoder) {
    super.init(coder: decoder)
    self.loadViewFromNib()
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    self.loadViewFromNib()
  }


  /** Loads instance from nib with the same name. */
  func loadViewFromNib() {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: .init(String(describing: type(of: self))), bundle: bundle)

    let myView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

    self.view = myView
    self.addSubview(myView)
  }

Any ideas what is going on? Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try to change the approach of your initialization.

Add an IBOutlet from the first view of your xib file to the swift file:

@IBOutlet var containerView: UIView!

Then edit your loadViewFromBib method as follow:

  func loadViewFromNib() {
    Bundle.main.loadNibNamed("DigitizingButton", owner: self, options: nil)
    addSubview(containerView)
    containerView.frame = self.bounds
    containerView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

    // Other initialization here
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...