2015-10-28 2 views
2

J'ai un CustomView.swift (sous-classe de UIView) connecté à CustomView.xib dans mon projet.Swift assigner le texte à l'étiquette dans le fichier xib

(note: définir la classe xib à CustomView mais n'a pas mis propriétaire)

Chargez le fichier xib dans CustomView.swift:

class CustomView: UIView { 

    @IBOutlet weak var label1: UILabel! 
    @IBOutlet weak var label2: UILabel! 

    /* 
    // Only override drawRect: if you perform custom drawing. 
    // An empty implementation adversely affects performance during animation. 
    override func drawRect(rect: CGRect) { 
     // Drawing code 
    }*/ 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     let subView: UIView = loadViewFromNib() 
     subView.frame = self.bounds 
     //label1.text = "123" //would cause error 
     addSubview(subView) 
    } 

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

    func loadViewFromNib() -> UIView { 
     let view: UIView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView 
     return view 
    } 
} 

Quelque part je fais la vue personnalisée:

let myCustomView:CustomView = CustomView.init(frame: CGRectMake(0, 0, 100, 100)) 
myCustomView.label1?.text = "123" 
myCustomView.label2?.text = "abc" 
print(myCustomView.label1.text)// returned nil 

Rien n'apparaît sur les étiquettes xib.

Dois-je écrire une extension pour CustomView.swift et ajouter une fonction d'affectation de texte?

Répondre

2

Vous devez charger de Nib

//let myCustomView:CustomView = CustomView.init(frame: CGRectMake(0, 0, 100, 100)) 
let myCustomView:CustomView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! CustomView 

myCustomView.label1?.text = "123" 
myCustomView.label2?.text = "abc" 
print(myCustomView.label1.text)