获取UIView的大小以编程方式添加子视图(具有计算出的X,Y,宽度和高度)

问题描述 投票:0回答:1

在segue中,我有一个UIVIew,它具有一些约束,使其布局与顶部,左侧和右侧的屏幕以及底部的按钮相同:enter image description here

然后从ViewController中以编程方式添加UIButtons,如下所示:

override func viewDidLoad() {
        super.viewDidLoad()

        drawCards()
    }


private func drawCards(){
        let deck = Deck()

        var rowIndex = 0
        var columnIndex = 0

        let cardWidth = Int(Float((deckView.bounds.width) / 7))
        let cardHeight = Int(Float(cardWidth) * 1.5)

        for card in deck.cards{
            let x = (cardWidth / 2) * columnIndex
            let y = cardHeight * rowIndex

            let button = CardButton()
            button.delegate = self
            button.setCard(card: card, x: x, y: y, width: cardWidth, height: cardHeight)

            deckView.addSubview(button)

            columnIndex += 1

            if(columnIndex == 13){
                columnIndex = 0
                rowIndex += 1
            }
        }
    }

预期的行为是此函数应采用UIView的大小(称为deckView),插入UIButtons并相互堆叠,并且在设备之间始终具有相同的布局。但是,在UIButtons超出UIView的范围内,它在iPhone上的显示效果与在iPad上的预期效果相同:enter image description here

据我所知,这是因为XY值计算不正确,因为UIViewdeckView)的宽度未正确检索(或按预期方式) 。

为什么UIView的宽度没有按预期方式获得?(即,为什么它在iPhone上能按预期工作,但在iPad上却不能按预期工作)

ios swift xcode uiview ios-autolayout
1个回答
1
投票

drawCards()viewDidLoad移动到viewDidLayoutSuviews

© www.soinside.com 2019 - 2024. All rights reserved.