更新:通过将init(coder)中的代码移动到layoutSubviews,我能够解决下面的问题。感谢您的投入!
我有一个视图类,它基本上构建了一个棋盘,并且具有1:1比例的约束和来自其他UI的一定数量的点。在init(编码器)中,我正在绘制板空间,然后调用一个函数来从我的控制器中绘制碎片。
但是,当我运行模拟器时,它不会基于设备加载,只会根据我目前在Interface Builder中选择的内容加载。
例如,我在IB中选择了iPhone 7 Plus但在iPhone 7上运行模拟器导致电路板离开屏幕。如果我在IB和模拟器中选择iPhone 7,它可以正常工作。
我一直难以找到这个问题的答案。任何帮助将不胜感激。
Because Storyboard set to iPhone 7 Plus
应用程序首先在init(编码器)中绘制空格:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let spaces: CGFloat = CGFloat(Constants.numberOfSpaces)
spaceMargin = 16
spaceWidth = (bounds.width - (spaces - 1) * spaceMargin) / spaces
spaceHeight = spaceWidth
pawnTop = bounds.height * (-3/304)
pawnMargin = bounds.width * (1/304)
pawnHeight = bounds.height * (48/304)
pawnWidth = bounds.width * (44/304)
pawnDict = [:]
spaceDict = [:]
for column in 0..<Constants.numberOfSpaces {
for row in 0..<Constants.numberOfSpaces {
let coordinate = try! Coordinate(column: column, row: row)
drawSpace(at: coordinate)
}
}
}
然后由我的控制器调用:
func updateBoard() {
guard let board = dataSource?.currentBoard() else {
return
}
// Remove previous pawns
for subview in subviews {
if let pawnView = subview as? PawnView {
pawnView.removeFromSuperview()
}
}
pawnDict = [:]
// Draw new pawns based on placement in board model
for column in 0..<Constants.numberOfSpaces {
for row in 0..<Constants.numberOfSpaces {
let coordinate = try! Coordinate(column: column, row: row)
let space = board.getSpace(coordinate)
if space.hasPawn {
drawPawn(at: coordinate)
}
}
}
}