【问题标题】:Incorrect frame values when using Stack Views使用堆栈视图时帧值不正确
【发布时间】:2015-07-26 22:34:46
【问题描述】:

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

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 值无关紧要,但奇怪的是,尽管检查器选项卡上有值,但宽度和高度值最终都为零。

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

【问题讨论】:

    标签: swift2 xcode7 ios9 uistackview


    【解决方案1】:

    在您的情况下,由于您尝试访问图像视图的框架并使用 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
        }
    

    希望这有帮助!

    【讨论】:

    • 成功了!我没有发现的是viewDidLayoutSubviews()。非常感谢!
    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2021-11-14
    相关资源
    最近更新 更多