Cannot Set Programmatic Layout Constraints in UIStackView

痞子三分冷 提交于 2019-12-24 20:52:45

问题


I am trying to center radiobuttons in UIStackView that I have created via the storyboard. However, the radiobuttons are created within the UIStackView programmatically based on data in Firebase.

I am using the library offered at DLRadioButtons.

UIStackView below Label, named radioStackView:

Code where Radio Buttons are added based on Firebase Data:

  `
    pollRef.observe(FIRDataEventType.value, with: {(snapshot) in
    self.numberOfChildren = Int(snapshot.childSnapshot(forPath: "answers").childrenCount)
    self.passLabel.text = String(self.numberOfChildren)
    print(self.numberOfChildren)

    var buttons = [DLRadioButton]()

      for x in 0..<self.numberOfChildren {
    let answerLabel = snapshot.childSnapshot(forPath: "answers").childSnapshot(forPath: String(x+1)).childSnapshot(forPath: "answer").value
    let firstRadioButton = self.createRadioButton(frame: CGRect(x: 1, y:1 , width: 80.0, height: 1.0), title: answerLabel as! String, color: UIColor.black)
        firstRadioButton.tag = x
        firstRadioButton.translatesAutoresizingMaskIntoConstraints = false
        buttons.append(firstRadioButton)
        let margins = self.radioStackView.layoutMarginsGuide
        firstRadioButton.topAnchor.constraint(equalTo: margins.topAnchor, constant: 5).isActive = true
        self.radioStackView.addArrangedSubview(firstRadioButton)
        }


    let groupButtons = DLRadioButton()
    groupButtons.otherButtons = buttons
    })



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

` Output: Buttons not stacking directly on top of each other; tried playing with interface builder but still unable to remove spacing


回答1:


To stack views in a stackView you need to use addArrangedSubview

self.radioStackView.addArrangedSubview(firstRadioButton)


来源:https://stackoverflow.com/questions/44171066/cannot-set-programmatic-layout-constraints-in-uistackview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!