[英]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 上却不是,因为UIButtons
在UIView
之外:
就我所知,这是因为X
和Y
值没有正确计算,因为UIView
( deckView
) 的宽度没有正确检索(或按预期)。
为什么没有按预期检索UIView
的宽度? (即为什么它在 iPhone 上按预期工作,但在 iPad 上却没有)
将drawCards()
从viewDidLoad
移动到viewDidLayoutSuviews
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.