UIView reference error

狂风中的少年 提交于 2019-12-25 07:49:16

问题


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

And this is my referencing.


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/41613567/uiview-reference-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!