获取 UIView 的大小以编程方式添加子视图(使用计算的 X、Y、宽度和高度)

Getting the size of an UIView to programmatically add subviews (with calculated X, Y, width and height)

在 segue 中,我有一个 UIVIew,它有一些限制,将其布局为与顶部、左侧和右侧的屏幕以及底部的按钮相同的大小:

然后从 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 并相互堆叠并具有相同的设备之间的布局一致。但是,它在 iPhone 上看起来符合预期,但在 iPad 上却不是,因为 UIButtons 超出了 UIView

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

为什么 UIView 的宽度没有按预期检索?(即为什么它在 iPhone 上按预期工作但在iPad)

将您的 drawCards()viewDidLoad 移动到 viewDidLayoutSuviews