UIView reference error

2019-09-11 18:58发布

I have created UIView in storyboard (Xcode 8.2.1). I reference the things inside to UIView class name LoginView. I delete one things by mistake then I got error at the line of Bundle.main.loadNibNamed("LoginView", owner: self, options: nil). EXC_BAD_ACCESS(code=2,....) I read about this in some answer here, they said about referencing missing. I try to reference everything again but still error. I'm now confusing about what should I reference it to. File Owner or View.

EDIT : The bug is happen when this View is render.

LoginView.swift

import UIKit

class LoginView: UIView {

@IBOutlet var view: UIView!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var forgotPasswordBtn: UIButton!

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

        Bundle.main.loadNibNamed("LoginView", owner: self, options: nil)
        self.addSubview(view)
        view.frame = self.bounds
        emailField.becomeFirstResponder()

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)

    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
}

This is my components in LoginView StoryBoard

enter image description here

And this is my referencing.

enter image description here

1条回答
祖国的老花朵
2楼-- · 2019-09-11 19:44

There's a CocoaPod called NibDesignable that not only configures the nib into the view (with constraints), but also makes the view IBDesignable so you can see your nib-based-views in the storyboard.

NibDesignable requires you to change the nib's file owner to the view class rather than the nib's view's custom class. Also, outlet connections must be made from the file's owner and not from the nib's view.

@IBDesignable class LoginView: NibDesignable {

    // MARK: Outlets

    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var passwordField: UITextField!
    @IBOutlet weak var forgotPasswordBtn: UIButton!

    // MARK: Properties

    var tap: UITapGestureRecognizer? {
        willSet {
            tap.flatMap { removeGestureRecognizer($0) }
        }
        didSet {
            tap.flatMap { addGestureRecognizer($0) }
        }
    }

    // MARK: Lifecycle

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        tap = UITapGestureRecognizer(
            target: self,
            action: #selector(didRecognizeTapGesture)
        )

        emailField.becomeFirstResponder()
    }

    // MARK: Actions

    @IBAction func didRecognizeTapGesture() {

        endEditing(true)
    }
}
查看更多
登录 后发表回答