繁体   English   中英

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

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

在 segue 中,我有一个UIVIew ,它具有约束,将其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 上却不是,因为UIButtonsUIView之外: 在此处输入图片说明

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

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

drawCards()viewDidLoad移动到viewDidLayoutSuviews

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM