问题
The example may look funny, but I am currently just trying to understand the methodology
I am trying to show several cards (subviews) in a vertical stack. Each card receives a CG figure from the same UIView class based on its position in the stack. But I seem to have a major misunderstanding of how the subviews defined in the storyboard work together with the code of the view controller.
On the storyboard, I have defined a superview with a vertical stack that contains 2 views. One of those subviews has a label "red", the other "blue".
If I now define the view controller
class SpatialViewController: UIViewController {
@IBOutlet var redSquare: SpatialProblemView!
@IBOutlet var blueSquare: SpatialProblemView!
override func viewDidLoad() {
super.viewDidLoad()
redSquare.subviewName = "red"
blueSquare.subviewName = "blue"
}
}
it will print both labels on top of each other (on the same position), although the vertical stack should place them above one another (as also shown on storyboard). Only when I insert an addSubview, the code as defined in the SpatialProblemView class is triggered. In this case also both sub views are correctly stacked, however, the position of the stack does not really comply with the constraints.
class SpatialViewController: UIViewController {
@IBOutlet var redSquare: SpatialProblemView!
@IBOutlet var blueSquare: SpatialProblemView!
override func viewDidLoad() {
super.viewDidLoad()
redSquare.subviewName = "red"
blueSquare.subviewName = "blue"
self.view.addSubview(redSquare)
self.view.addSubview(blueSquare)
}
}
I would have expected that the storyboard itself has created an instance of both sub views, which are then connected with the IBOutlet to the view controller.
(1) So why do I have to call addSubview to get a proper layout of both subviews and to get the code within SpatialProblemView triggered?
(2) Why doesn't the positioning of the stack match the constraints of the storyboard (should be horiz/vert centered, is left and partially above top of superview) and how can I correct this? My understanding is, I cannot use programatical methods to manipulate a storyboard view.
来源:https://stackoverflow.com/questions/62692861/swift-issue-with-collaboration-of-view-from-storyboard-with-code-in-viewcontrol