Mixing programmatic and IB design

forgive me if I am positing in the wrong place, I am new to the forum and to Swift/Xcode

I am trying to mix programmatic code and IB elements.

import UIKit


class ViewController: UIViewController {

override func viewDidLoad() {
let fff = ff(frame: self.view.frame)
// Have also tried self.view = fff

This all works fine and I can add buttons etc to it as needed.

BUT I am trying to do some programmatically and adding for example a button using the IB

But the IB button does not show,

I am obviously doing something silly / not doing something // or just lack a fundamental grapsp of the View hierarchy

Can you advise please

This isn't really a Swift question - you'd probably get more relevant help on a different forum.

However, your immediate problem is most likely that your programmatically-created view is both opaque and on top of any views you might have added in IB.

Thank you, and noted about the forum.

Just if I may though, yes you are right - I can now see the IB button.
So I think my real question is probably this.

Given that the UIView I created programmatically was set to self.view = fff (the view I created programatically) WHY is this not the one I am editing in IB?

OR I guess how do I make it the one I am editing in IB - so that I can add elements programatically and by IB on the same view?

thanks very much again

self.view is already set to the view created in IB, so it already contains one button at the start of viewDidLoad. To add further subviews, you are correct in using self.view.addSubview.

Rather than creating a new view in ff and customising that, I recommend you just use the existing self.view. For example, to add a second button in addition to the one created in IB, you should use self.view.addSubview(myButton).

Reassigning the view with self.view = fff will swap out the view containing the button, with the view you created through code. Swapping out the view isn't generally recommended.

1 Like

Brilliant, thank you very much indeed James.
Yes that makes sense.

Terms of Service

Privacy Policy

Cookie Policy