with from custom create ios swift uiview nib

ios - from - Propiedades de IBOutlet nulas después de una vista personalizada cargada desde xib



swift xib (4)

¿Y cómo iniciaste tu vista desde el controlador? Me gusta esto:

var view = CustomKeyboard.keyboard() self.view.addSubview(view)

Algo extraño está pasando con IBOutlets.

En el código he intentado acceder a estas propiedades, pero son nil . Código:

class CustomKeyboard: UIView { @IBOutlet var aButt: UIButton! @IBOutlet var oButt: UIButton! class func keyboard() -> UIView { let nib = UINib(nibName: "CustomKeyboard", bundle: nil) return nib.instantiateWithOwner(self, options: nil).first as UIView } override init() { super.init() commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } // MARK: - Private private func commonInit() { println(aButt) // aButt is nil aButt = self.viewWithTag(1) as UIButton println(aButt) // aButt is not nil } }


Es posible que su punta no esté conectada. Mi solución es bastante simple. En algún lugar de su proyecto (creo una clase llamada UIViewExtension.swift), agregue una extensión de UIView con este práctico método connectNibUI.

extension UIView { func connectNibUI() { let nib = UINib(nibName: String(describing: type(of: self)), bundle: nil).instantiate(withOwner: self, options: nil) let nibView = nib.first as! UIView nibView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(nibView) //I am using SnapKit cocoapod for this method, to update constraints. You can use NSLayoutConstraints if you prefer. nibView.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self) } } }

Ahora puede llamar a este método en cualquier vista, en su método init, haga esto:

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


Eso se espera, porque los IBOutlet (s) no se asignan en el momento en que se llama al inicializador. No necesita commonInit, solo una anulación de awakeFromNib de la siguiente manera:

override func awakeFromNib() { super.awakeFromNib() print(aButt) }


Suponiendo que haya intentado los pasos estándar de solución de problemas para conectar IBOutlets, intente esto:

Aparentemente, debe desactivar la función Despertar de la punta en ciertos casos de tiempo de ejecución.

override func awakeAfter(using aDecoder: NSCoder) -> Any? { guard subviews.isEmpty else { return self } return Bundle.main.loadNibNamed("MainNavbar", owner: nil, options: nil)?.first }