Search code examples
iosswiftconstraintsxib

Weird constraints/UI bug with view from xib


I'm creating a pull-up google-maps-esque bottom drawer view, which looks like this (when it works):

enter image description here

That bottom drawer view is loaded from a xib: enter image description here

The issue is that sometimes the view shows up like this:

enter image description here enter image description here enter image description here

This seems like a constraints issue, but I think my constraints are all correct. CardView is constrained to the superview on all sides and the pink join button is constrained to the right edge, top, and bottom, and has a greater-than-or-equal-to constraint to the text label to the left.

enter image description here

enter image description here

I'm a bit new to using xibs, so maybe this issue has to do with how I'm instantiating it? Here are my xib init methods:

override init(frame: CGRect) {
    super.init(frame: frame)
    loadFromXib()
}

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

func loadFromXib() {
    // standard initialization logic
    Bundle.main.loadNibNamed("ChatroomCardView", owner: self, options: nil)
    contentView!.frame = bounds
   // contentView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    addSubview(contentView!)

    cardView.layer.shadowOffset = CGSize(width: 0, height: -3.0)
    cardView.layer.shadowRadius = 3.0
    cardView.layer.shadowOpacity = 0.6
    cardView.layer.masksToBounds = false

    joinButton.setRadiusWithShadow()
}

and here is how I instantiate a cardview (the first two lines):

// create small view
let chatroomCardView = ChatroomCardView(frame: CGRect(x: 0, y: 0, width: 375, height: 139))
chatroomCardView.chatRoom = chatRoom


// create fullsize view
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let chatroomDetailVC = storyboard.instantiateViewController(withIdentifier: "ChatRoomDetailVC") as! ChatRoomDetailVC
chatroomDetailVC.chatroom = chatRoom

bottomDrawerVC.mainFullVC = chatroomDetailVC
bottomDrawerVC.smallDrawerView = chatroomCardView
bottomDrawerVC.view.addSubview(bottomDrawerVC.mainFullVC.view)
bottomDrawerVC.view.addSubview(bottomDrawerVC.smallDrawerView)

I'm really stumped on what the issue could be, so any help would be greatly appreciated.


Solution

  • You are adding your view as a subview of your view controller's view, but where are you creating the constraints between these two views? You may have constraints for the subviews of chatroomCardView, but you still need to programmatically create constraints between chatroomCardView and its super view. ie something along the lines of translatesAutoresizingMaskIntoConstraints = false, and then bottomAnchor to bottomAnchor, leadingAnchor to leadingAnchor, trailingAnchor to trailingAnchor and a constant height constraint, or just shove both subviews into a vertical stackview.