0

I'm having an issue i can't figure out. I need to build a widget and i have two custom views (Right now using the same custom view)

The issue is that for some reason they stack on each other (I can see that in the first print i have on sub view and in the second one i have two and see only the second subview constraint to the top of the containing view)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded

    guard let currentView = Bundle.main.loadNibNamed("CurrentView", owner: self, options: nil)?.first as? CurrentView else { return  }

    currentView.frame = self.view.frame
    self.view.addSubview(currentView)

    currentView.forcastImage.image = #imageLiteral(resourceName: "13")

    currentView.translatesAutoresizingMaskIntoConstraints = false
    currentView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    currentView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
    currentView.heightAnchor.constraint(equalToConstant: 110).isActive = true

    print(self.view.subviews.count)

    if let hourlyView = Bundle.main.loadNibNamed("CurrentView", owner: self, options: nil)?.first as? CurrentView {
        hourlyView.frame = self.view.frame
        self.view.addSubview(hourlyView)

        hourlyView.forcastImage.image = #imageLiteral(resourceName: "6")

        hourlyView.translatesAutoresizingMaskIntoConstraints = false
        hourlyView.topAnchor.constraint(equalTo: currentView.bottomAnchor, constant: 150).isActive = true
        hourlyView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        hourlyView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        hourlyView.heightAnchor.constraint(equalToConstant: 110).isActive = true
    }

    print(self.view.subviews.count)
}

func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
    if activeDisplayMode == .expanded {

        preferredContentSize = CGSize(width: 0, height: 250)
    } else {
        preferredContentSize = maxSize
    }
}

Any idea why is that?

Erez
  • 1,933
  • 5
  • 29
  • 56

1 Answers1

1

You may need

currentView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10).isActive = true
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • I'm so stupid :-) changed a little bit you answer but this solved everything how did i miss that? currentView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true – Erez Dec 10 '19 at 12:35