iosswiftxibnib

UIView instanceFromNib() function


I am trying to present a custom keyboard that I built in an xib file, when I instantiate the class I need to pass some variables to that class in order to make things work correctly, but I am getting this error: Instance member 'target' cannot be used on type 'CustomKeyboardView'

on the lines

 self.target = target
 self.section = section


class CustomKeyboardView: UIView {
    
    weak var target:UIKeyInput?
    var section:Int?
    
    class func instanceFromNib(target: UIKeyInput, section: Int) -> UIView {
        self.target = target
        self.section = section
        return UINib(nibName: "CustomKeyboard", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}

How can I fix this or pass the info to the class in a different way?


Solution

  • You try to set value to the class type not to an instance. First get the keyboard from nib then set its properties and return it :

    class func instanceFromNib(target : UIKeyInput, section : Int) -> UIView {
        let keyboard = UINib(nibName: ...
        keyboard,target = target
        keyboard.section = section
        return keyboard
    }