I have a small xib, Teste.xib
owned by TesteView
class TesteView: UIView {
@IBOutlet var tf:UITextField!
@IBOutlet var sw:UISwitch!
}
Now, we're gonna load it (and for example stuff it in a stack view).
let t:TesteView = TesteView()
let v = Bundle.main.loadNibNamed("Teste", owner: t, options: nil)?[0] as! UIView
v.heightAnchor.constraint(equalToConstant: 200).isActive = true
stack?.insertArrangedSubview(v, at: 3)
in fact, that's fine.
Everything works.
But note that you insert "v", not "t". "v" is not "the TesteView", it's just some damned view that is floating around.
If you do the following,
t.heightAnchor.constraint(equalToConstant: 200).isActive = true
stack?.insertArrangedSubview(t, at: 3)
it is meaningless, that doesn't work.
But t "is" the view, it's a UIView (indeed, it is a TesteView). It should be the thing you insert.
So you have to use the "two different" things ...
t.tf.text = "WTF???"
// use "t" for that sort of thing
v.heightAnchor.constraint(equalToConstant: 200).isActive = true
v.backgroundColor = UIColor.blue
// but use "v" for that sort of thing
stack?.insertArrangedSubview(v, at: 3)
It seems weird that "t" and "v" are not the same.
(Indeed, should TesteView even have been a subclass of UIView? Maybe it should be something else - just a plain class?? It seems one can not really use it as a view so WTF is it??)
What's the deal on this and/or what is the usual idiom?
NOTE ...
nowadays, there is no reason to ever do this. Just use a small UIViewController. For decades everyone said "Why doesn't apple let you simply load a view controller by id?", well now you can. No problems:
let t = self.storyboard?.instantiateViewController(withIdentifier: "TesteID") as! Teste
t.view.heightAnchor.constraint(equalToConstant: 200).isActive = true
stack?.insertArrangedSubview(t.view, at: 3)
t.tex.text = "WTH???"