Westerlund.io
Westerlund.io

Reputation: 2833

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: enter image description here

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: enter image description here

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? (i.e. why does it works as expected on iPhone but not on iPad)

Upvotes: 0

Views: 544

Answers (1)

user12688502
user12688502

Reputation:

Move your drawCards() from viewDidLoad to viewDidLayoutSuviews

Upvotes: 1

Related Questions