Get the frame of a UIStackView subViews

南楼画角 提交于 2019-12-10 15:39:35

问题


I have created a UIStackView in IB which has the distribution set to Fill Equally. I am looking to get the frame for each subView but the following code always returns (0, 0, 0, 0).

class ViewController: UIViewController {
    @IBOutlet weak var stackView: UIStackView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let pView = UIView()
        let sView = UIView()

        pView.backgroundColor = UIColor.red
        sView.backgroundColor = UIColor.orange

        stackView.addArrangedSubview(pView)
        stackView.addArrangedSubview(sView)
    }

    override func viewDidLayoutSubviews() {
        print(stackView.arrangedSubviews[0].frame)
        print(stackView.arrangedSubviews[1].frame)
    }
}

I would think that a stack view set to fill equally would automatically set the calculate it.

Any help would be appreciated.


回答1:


After reading over your code I think this is just a misunderstanding of viewDidLayoutSubviews(). Basically it is called when all the views that are descendants of the main view have been laid out but this does not include the subviews(descendants) of these views. See discussion notes from Apple.

"When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout."

Now there are many ways to get the frame of the subviews with this being said.

First you could add one line of code in viewdidload and get it there.

    override func viewDidLoad() {
    super.viewDidLoad()

    let pView = UIView()
    let sView = UIView()

    pView.backgroundColor = UIColor.red
    sView.backgroundColor = UIColor.orange

    stackView.addArrangedSubview(pView)
    stackView.addArrangedSubview(sView)
    stackView.layoutIfNeeded()
    print(stackView.arrangedSubviews[0].frame)
    print(stackView.arrangedSubviews[1].frame)

}

OR you can wait until viewDidAppear and check there.

 override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    print(stackView.arrangedSubviews[0].frame)
    print(stackView.arrangedSubviews[1].frame)
}


来源:https://stackoverflow.com/questions/42890174/get-the-frame-of-a-uistackview-subviews

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