Mohsin
Mohsin

Reputation: 463

Custom views are not showing up properly

I am trying to show 3 custom views in an iOS screen but only one of them is showing up. 2nd one started showing up a bit in improper way after putting alot of constraints and third one is completely not showing up.For test I am calling the same view three times. See the code. I have just started doing iOs so just forgive me if I am making any blunder or obvious mistake.

I have tried to put constraints accordingly, put a scrollview behind but none of this seems to be working

I am getting this result Here is storyboard screenshot and constraints

I have remover container3 from storyboard because when I add it, the container2 doesn't show-up even slightly. Please help me with this layout problem.

class TestCustomViewController: UIViewController {

@IBOutlet weak var container : UIView?

@IBOutlet weak var container2 : UIView?

@IBOutlet weak var container3 : UIView?

var testView: CustomView!
var testView2: CustomView!
var testView3: CustomView!
override func viewDidLoad() {
    super.viewDidLoad()
    ////////First View//////
   testView = createGearItemView()
    testView.frame = (container?.frame)!
    container?.addSubview(testView)
    /////////Second View//////
    testView2 = createGearItemView()
    testView2.frame = (container2?.frame)!
    container2?.addSubview(testView2)
    ////// THird View/////////
    testView3 = createGearItemView()
    testView3.frame = (container3?.frame)!
    container3?.addSubview(testView3)
}

func createGearItemView () -> CustomView {
    let view = (Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView)!

    view.backgroundColor = UIColor.clear
    return view
}

}

Upvotes: 0

Views: 681

Answers (1)

André Slotta
André Slotta

Reputation: 14040

Except of the fact that you should familiarize yourself with Auto Layout (see Understanding Auto Layout) you have to use the containers' bounds as frames for your subviews (although it might not be the correct ones yet in viewDidLoad):

testView.frame = (container?.bounds)!
...

An even better way is using Auto Layout for your subviews instead of setting the frames directly:

testView = createGearItemView()
container?.addSubview(testView)
testView.translatesAutoresizingMaskIntoConstraints = false
testView.topAnchor.constraint(equalTo: container!.topAnchor).isActive = true
testView.leadingAnchor.constraint(equalTo: container!.leadingAnchor).isActive = true
testView.bottomAnchor.constraint(equalTo: container!.bottomAnchor).isActive = true
testView.trailingAnchor.constraint(equalTo: container!.trailingAnchor).isActive = true
testView2...

Upvotes: 1

Related Questions