'How can I manage this view when constraints aren't available to me in swiftui?
I am very new to SwiftUI, and have actually been getting the hang of arranging my views using the Z, V and HStacks. But the lack of a centre anchor is proving difficult to manage views which need to be anchored to different anchors of other views; as in the following case:
The Blue thing is a popUp and I have anchored the centreY anchor of the button to the bottom anchor of the popUp view, using the following code:
popUpView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
popUpView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
popUpView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
popUpView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.45),
myButton.centerXAnchor.constraint(equalTo: popUpView.centerXAnchor),
myButton.centerYAnchor.constraint(equalTo: popUpView.bottomAnchor),
myButton.widthAnchor.constraint(equalTo: popUpView.widthAnchor, multiplier: 0.285),
myButton.heightAnchor.constraint(equalTo: popUpView.heightAnchor, multiplier: 0.2),
Is there any way to manage this using stacks in SwiftUI?
Solution 1:[1]
If you already have such popUpView
and myButton
components prepared in SwiftUI, the alignment like on screen can be done actually in two lines
struct ContentView: View {
var body: some View {
ZStack(alignment: .bottom) { // << here !!
PopUpView()
MyButton()
.alignmentGuide(.bottom) { $0.height / 2 } // << here !!
}
}
}
Solution 2:[2]
The offset will depend on the height of the custom button (I put 20 as example).
struct ContentView: View {
var body: some View {
VStack {
PopUpView()
MyButton()
.offset(y: -20)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Asperi |
Solution 2 | Cristian Zumelzu |