简体   繁体   中英

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

In a segue I have an UIVIew which have constraints that lays it out to the same size as the screen on the top, left and right as well as to a button on the bottom: 在此处输入图片说明

Then from the ViewController I programmatically add UIButtons like this:

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
            }
        }
    }

The expected behavior is that this function should take the size of the UIView (called deckView ), insert the UIButtons and to be stacked over each other and have the same layout consistently between devices. However, it looks as expected on iPhone but not on iPad as the UIButtons go outside of the UIView : 在此处输入图片说明

This is, as for as I can tell, because the X and Y values aren't calculated correctly because the width of the UIView ( deckView ) isn't retrieved correctly (or as expected).

Why isn't the width of the UIView being retrieved as expected? (ie why does it works as expected on iPhone but not on iPad)

drawCards()viewDidLoad移动到viewDidLayoutSuviews

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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