使用堆栈视图时不正确的帧值

Incorrect frame values when using Stack Views

我将两张图片放在一个堆栈视图中。我想以编程方式将这两个方形图像转换为圆形,所以我使用以下代码。

class ProfileViewController: UIViewController {
    @IBOutlet weak var image1: UIImageView!
    @IBOutlet weak var image2: UIImageView!

    override viewDidLoad(){
        // Convert image one into circle
        self.image1.layer.cornerRadius = self.image1.frame.height/2
        self.image1.clipsToBounds = true

        // Convert image two into circle
        self.image2.layer.cornerRadius = self.image2.frame.height/2
        self.image2.clipsToBounds = true

        // Print the frames of these two images
        print(self.image1.frame)
        print(self.image2.frame)
    }
}

在示例中,框架的 x 和 y 值无关紧要,但奇怪的是,尽管检查器选项卡上有值,但宽度和高度值最终都为零。

如果我在屏幕上添加一个按钮,然后打印出两个图像的帧,我将获得预期的宽度和高度值。因此,我假设 Stack Views 在 viewDidLoad() 方法触发后确定对象的尺寸。在这种情况下,获得实际帧尺寸以使两幅图像四舍五入的最佳方法是什么?或者使用 frame 以外的值会是更好的解决方案吗?

在您的情况下,由于您正在尝试访问图像视图的框架并使用 UIStackView,因此框架实际上将首先布置在 viewDidLayoutSubviews() 中。所以要获得你想要的圆形图像,你需要首先为堆栈视图创建一个出口:

class ProfileViewController: UIViewController {
    @IBOutlet weak var verticalStackView: UIStackView!

    ...

然后在 viewDidLayoutSubviews() 方法中,访问堆栈视图的 arrangedSubviews 的索引以获取图像所在的视图(索引可以从堆栈视图层次结构中确定,去从上到下)然后像你一直做的那样得到圆角:

class ProfileViewController: UIViewController {
    @IBOutlet weak var verticalStackView: UIStackView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidLayoutSubviews() {
        let myImage = verticalStackView.arrangedSubviews[1] //in my test my image was the second view in the stack view hierarchy

        myImage.layer.cornerRadius = myImage.frame.height/2
        myImage.clipsToBounds = true
    }

希望对您有所帮助!