获取UIStackView子视图的框架 [英] Get the frame of a UIStackView subViews

查看:310
本文介绍了获取UIStackView子视图的框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IB中创建了一个UIStackView,其分布设置为均等填充".我正在寻找每个subView的框架,但是以下代码总是返回(0,0,0,0).

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.

任何帮助将不胜感激.

推荐答案

阅读完您的代码后,我认为这只是对viewDidLayoutSubviews()的误解.基本上,当所有作为主视图后代的视图均已布局,但不包括这些视图的子视图(后代)时,将调用此方法.请参阅来自苹果的讨论注释.

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.

首先,您可以在viewdidload中添加一行代码并将其添加到那里.

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)

}

或者您可以等到viewDidAppear并在那里检查.

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)
}

这篇关于获取UIStackView子视图的框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆