как создать пользовательский вид с использованием xib - PullRequest
0 голосов
/ 12 июня 2019

Я создал пользовательское представление, которое можно использовать повторно в нескольких местах, я назначил это имя класса для вспомогательного представления контроллера представления. Здесь я полностью использую XIB. При запуске этого приложения происходит сбой и возникает ошибка "Поток 1: EXC_BAD_ACCESS (code = 2, address = 0x7ffeee23be2c) "в строке" Bundle.main.loadNibNamed ("TripCancelAlert", владелец: self, параметры: nil) "

Просмотреть класс:

class TripCancelAlert: UIView {


    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

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

    func commonInit() {
        Bundle.main.loadNibNamed("TripCancelAlert", owner: self, options: nil)
       // self.addSubview(contentView)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

1 Ответ

1 голос
/ 12 июня 2019

Найдите под своим надклассом суперкласс.

Обязательно назовите ваш xib с тем же именем, что и ваш class (MyView.xib / MyView)

class NibView: UIView {

    @IBOutlet var view: UIView!

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

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    func commonInit() {
        guard let viewFromNib = Bundle.main.loadNibNamed(className, owner: self, options: nil)?.first as? UIView
            else { fatalError("Could not load view from nib file.") }
        view = viewFromNib
        translatesAutoresizingMaskIntoConstraints = false
        view.translatesAutoresizingMaskIntoConstraints = false
        addPinnedSubview(view)

    }

    func addPinnedSubview(_ view: UIView, withInsets insets: UIEdgeInsets = .zero) {
        addSubview(view)
        let viewsDict: [String: UIView] = ["childView": view]
        var metrics: [String: Any] = [:]
        metrics["topSpace"] = insets.top
        metrics["bottomSpace"] = insets.bottom
        metrics["leftSpace"] = insets.left
        metrics["rightSpace"] = insets.right
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topSpace)-[childView]-(bottomSpace)-|",
                                                      options: [],
                                                      metrics: metrics,
                                                      views: viewsDict))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftSpace)-[childView]-(rightSpace)-|",
                                                      options: [],
                                                      metrics: metrics,
                                                      views: viewsDict))
    }
}
...