在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
之外:
据我所知,这是因为 X
和 Y
值未正确计算,因为 UIView
的宽度> (deckView
) 未正确检索(或按预期)。
为什么没有按预期检索 UIView
的宽度?(即为什么它在 iPhone 上按预期工作,但在 iPad 上却不然)
最佳答案
将 drawCards()
从 viewDidLoad
移动到 viewDidLayoutSubviews
关于ios - 获取 UIView 的大小以编程方式添加 subview (计算出的 X、Y、宽度和高度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960341/