I'm trying to build a simple watchOS UI with SwiftUI with two pieces of information side-by-side above a button.
I'd like each side (represented as a VStack within an HStack) to take up half of the available width (so it's an even 50/50 split within the yellow parent view) divided where the | character is centered on the button in the example below.
I want the Short and Longer!!! text to each be centered within each side's 50%.
I started with this code, to get the elements in place and show the bounds of some of the different stacks:
var body: some View {
VStack {
HStack {
VStack {
Text("Short").font(.body)
}
.background(Color.green)
VStack {
Text("Longer!!!").font(.body)
}
.background(Color.blue)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.yellow)
Button (action: doSomething) {
Text("|")
}
}
}
Which gave me this result:
Then, when it comes to making each side-by-side VStack 50% of the available width, I'm stuck. I thought it should work to add .relativeWidth(0.5) to each VStack, which should, as I understand it, make each VStack half the width of its parent view (the HStack, with the yellow background):
var body: some View {
VStack {
HStack {
VStack {
Text("Short").font(.body)
}
.relativeWidth(0.5)
.background(Color.green)
VStack {
Text("Longer!!!").font(.body)
}
.relativeWidth(0.5)
.background(Color.blue)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.yellow)
Button (action: doSomething) {
Text("|")
}
}
}
But this is the result I get:
How can I get the behavior I want with SwiftUI?
Update: After reviewing the SwiftUI documentation more, I see the example here that sets a frame and then defines a relative width in comparison to that frame, so maybe I'm not supposed to use relativeWidth in this way?
I'm a step closer to what I want with the following code:
var body: some View {
VStack {
HStack {
VStack {
Text("Short").font(.body)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.green)
VStack {
Text("Longer!!!").font(.body)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.blue)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.yellow)
Button (action: doSomething) {
Text("|")
}
}
}
which produces this result:
Now, I am trying to figure out what's creating that extra space in the middle between the two VStacks. So far, experimenting with getting rid of padding and ignoring safe areas does not seem to affect it.
I'm still confused about when and how relativeWidth is supposed to be used, but I was able to achieve want I wanted without using it. (EDIT 18 July 2019: According to the iOS 13 Beta 4 release notes, relativeWidth is now deprecated)
In the last update to my question I had some extra spacing between the two sides, and realized that was the default spacing coming in on the HStack and I was able to remove that by setting its spacing to 0. Here's the final code and result:
var body: some View {
VStack {
HStack(spacing: 0) {
VStack {
Text("Short").font(.body)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.green)
VStack {
Text("Longer!!!").font(.body)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.blue)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.yellow)
Button (action: doSomething) {
Text("|")
}
}
}
And here is the result:
Here's how to create an EqualWidthHStack for watchOS 9, iOS 16, tvOS 16 & macOS 13
Here's the usage:
struct ContentView: View {
private let strings = ["Hello,", "very very very big", "world!"]
var body: some View {
EqualWidthHStack {
ForEach(strings, id: \.self) { string in
ZStack {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.opacity(0.2)
Text(string)
.padding(10)
}
}
}
}
}
First create a struct that conforms to Layout.
struct EqualWidthHStack: Layout {
...
}
It will come with two default methods, here's how you can implement them.
Size that Fits:
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let maxSize = maxSize(subviews: subviews)
let spacing = spacing(subviews: subviews)
let totalSpacing = spacing.reduce(0.0, +)
return CGSize(width: maxSize.width * CGFloat(subviews.count) + totalSpacing,
height: maxSize.height)
}
Place Subviews:
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let maxSize = maxSize(subviews: subviews)
let spacing = spacing(subviews: subviews)
let sizeProposal = ProposedViewSize(width: maxSize.width,
height: maxSize.height)
var x = bounds.minX + maxSize.width / 2
for index in subviews.indices {
subviews[index].place(at: CGPoint(x: x, y: bounds.midY),
anchor: .center,
proposal: sizeProposal)
x += maxSize.width + spacing[index]
}
}
You will need the following two helper methods.
Max Size:
private func maxSize(subviews: Subviews) -> CGSize {
let subviewSizes = subviews.map { $0.sizeThatFits(.unspecified) }
let maxSize: CGSize = subviewSizes.reduce(.zero, { result, size in
CGSize(width: max(result.width, size.width),
height: max(result.height, size.height))
})
return maxSize
}
Spacing:
private func spacing(subviews: Subviews) -> [CGFloat] {
subviews.indices.map { index in
guard index < subviews.count - 1 else { return 0.0 }
return subviews[index].spacing.distance(to: subviews[index + 1].spacing,
along: .horizontal)
}
}
Here's Apples WWDC22 video on how to make it:
Compose custom layouts with SwiftUI
You have set background of HStack to yellow color and HStack has some default inter child views spacing. By adding spacing: 0 in HStack will solve the problem see the updated code below.
var body: some View {
VStack {
HStack(spacing: 0) { // Set spacing here
VStack {
Text("Short").font(.body)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.green)
VStack {
Text("Longer!!!").font(.body)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.blue)
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.yellow)
Button (action: doSomething) {
Text("|")
}
}
}
Related
Context menu background not updated
I am trying to update background colour.
Background colour is updated for view, but it is not getting updated for the context menu
Context menu shows previous colour which was set.
can someone help me with this.
thanks in advance
this is the code i used
import SwiftUI
struct ContextMenu: View {
/*List of items =*/
#State var bgColor = Color.gray
var body: some View {
HStack {
Rectangle().frame(width: 120, height: 120).opacity(0.01).border(Color.black, width: 1).contextMenu{
VStack {
Button("Orange",action: {
self.bgColor = Color.orange
})
Button("Green",action: {
self.bgColor = Color.green
})
Button("Red",action: {
self.bgColor = Color.red
})
}
}
}.frame(width:UIScreen.main.bounds.width, height: 200).background(bgColor)
}
}
Context menu caches content and reuse it all the time. Here is possible solution to force update it.
Tested with Xcode 11.4 / iOS 13.4
HStack {
Rectangle().fill(bgColor) // << use same color
.frame(width: 120, height: 120)
.border(Color.black, width: 1)
.contextMenu{
VStack {
Button("Orange",action: {
self.bgColor = Color.orange
})
Button("Green",action: {
self.bgColor = Color.green
})
Button("Red",action: {
self.bgColor = Color.red
})
}
}.id(UUID()) // << force recreate context menu
}.frame(width:UIScreen.main.bounds.width, height: 200).background(bgColor)
When I apply the scrollview it pushes my whole view up and leaves a white space below the bottom of the ZStack. Not sure why but if someone can please help.
var body: some View {
ZStack{
GeometryReader { geometry in
Spacer()
ScrollView (.vertical, showsIndicators: false) {
VStack (spacing : self.Vspacing){
Spacer()
ForEach (self.buttons, id: \.self) { row in
SportsButtonsRow(screenWidth: geometry.size.width,
Hspacing: self.Hspacing,
buttons: row, didTapButton: { sportButton in self.displayText = sportButton.title}
)
}//end foreach
// Spacer ()
}.background(Color.black)//end of VStack
}//end of scroll view
}//close geometry reader
}//end of ZStack
.edgesIgnoringSafeArea(.all)
}//end of main some View
}
You need to change the order of containers construction. The following scratch demo works:
var body: some View {
ZStack{
GeometryReader { geometry in
ScrollView (.vertical, showsIndicators: false) {
// YOUR CONTENT HERE
}
.background(Color.black)//end of VStack
.frame(height: geometry.size.height)
//end of scroll view
} //close geometry reader
.edgesIgnoringSafeArea(.all)
} //end of ZStack
} //end of main some View
I figured it out. It seems you need to designate a frame size for the scrollview so I did.
GeometryReader { geometry in
Spacer()
VStack{
Text ("fdklafdfa")
.foregroundColor(.blue)
.frame(width: geometry.size.width, height:geometry.size.height * 0.32 , alignment: .bottom)
Spacer()
ScrollView (.vertical, showsIndicators: false) {
VStack (spacing : self.Vspacing){
Spacer()
ForEach (self.buttons, id: \.self) { row in
SportsButtonsRow(screenWidth: geometry.size.width,
Hspacing: self.Hspacing,
buttons: row, didTapButton: { sportButton in self.displayText = sportButton.title}
)
}//end foreach
// Spacer ()
}//end of VStack
}//end of scroll view
.frame(width: geometry.size.width, height:geometry.size.height * 0.68 , alignment: .bottom)
.edgesIgnoringSafeArea(.all)
.background(Color.black)
}//End of main VStack
}//close geometry reader
I'am developing an app with swift ui. It's a single View App. But I have a problem with the scrollView
I have tried to delete the scrollview but it didn't change anything. I always have this big white problem on the top of my view.
https://imgur.com/a/BiWy0fe
import SwiftUI
struct Redactor {
var id: Int
let name, imageURL, since, bio: String
}
struct Article {
var id: Int
let name, image, content, redactor: String
}
struct MainScreenView: View {
let redactors:[Redactor] = [...]
let articles:[Article] = [...]
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: .leading) {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 20) {
ForEach(redactors, id: \.id) { Redactor in
NavigationLink(destination: MainRedactorView(redactor: Redactor)) {
RedactorView(redactor: Redactor)
}
}
}.padding(.leading, 15)
}.padding(.top, 10)
VStack(alignment: .leading) {
Text("Les Dernières nouvelles :")
.font(.title)
.fontWeight(.bold)
.padding(.leading, 15)
.padding(.top, 20)
ForEach(articles, id: \.id) { Article in
ArticleView(article: Article)
}
}
}
}
.navigationBarTitle(Text("The News Place"))
}
}
}
struct RedactorView: View {
let redactor : Redactor
var body : some View {
VStack {
Image(redactor.imageURL)
.resizable()
.frame(width: 150, height: 150)
.aspectRatio(contentMode: .fill)
.cornerRadius(75)
Text(redactor.name)
.font(.subheadline)
.fontWeight(.bold)
}
}
}
struct ArticleView: View {
var article: Article
var body: some View {
VStack (alignment: .leading) {
Image(article.image)
.renderingMode(.original)
.resizable()
.cornerRadius(10)
.aspectRatio(contentMode: .fit)
Text(article.name)
.font(.title)
.fontWeight(.bold)
Text("Le Rondeau Mag'")
.font(.subheadline)
.foregroundColor(.red)
Text(article.content)
.font(.body)
.lineLimit(5)
.foregroundColor(.secondary)
}.padding()
}
}
I would like to delete this white blank on the top of my scroll view. Thank you
Did you try deleting the VStack inside ScrollView? ScrollView already defines an implicit stack.
A good way to know which element causes the blank space is applying .border(Color.red) to different views.
Hope this helps.
Is the NavigationView that's creating the white space on top.
Try with
.navigationBarTitle(Text("The News Place"), displayMode: .inline)
and see if the white space disappears.
I have a "card" view that can be swiped left or right which contains a TextField. However, the TextField is not allowing me to edit it. I do not understand this. Every tutorial I see, the TextField edits with no issue. What am I doing wrong here?
EDIT: I've figured out that the TextField is being used as part of the gesture recognition. I can drag on the TextField and it will move the whole card. How do I make the textfield not draggable yet remain part of the card and drag when the image is dragged?
return VStack {
Image("food")
.resizable()
.aspectRatio(1.0, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 50))
TextField("Leave a comment", text: $comment) {
self.commentText = self.comment
}
.padding()
.background(Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0), cornerRadius: 10.0)
}
.padding()
.shadow(color: Color.black, radius: 15, x: 2, y: 2)
.offset(
x: viewState.width + dragState.translation.width
)
.gesture(longPressDrag)
.presentation($showAlert) {
Alert(title: Text("User commented on this photo!"), message: Text(commentText), primaryButton: .default(Text("OK")) {
self.viewState = CGSize.zero
}, secondaryButton: .cancel()
)
}
}
}
What is the correct way of asking the bounds of Flickable.contentY? I need that for a scrollbar.
Experimentally I have discovered that
offsetY <= contentY <= offsetY + contentHeight - height
where offsetY can be calculated as
var offsetY = contentY-Math.round(visibleArea.yPosition*contentHeight)
offsetY is zero at the start of the application and seems to be constant unless Flickable is resized.
This formula works in general, but there probably should be a dedicated function for it.
I did a scrollbar easily without offset :
// ScrollBar.qml
import QtQuick 2.0
Rectangle {
id: scrollbar;
color: "#3C3C3C";
visible: (flicker.visibleArea.heightRatio < 1.0);
property Flickable flicker : null;
width: 20;
anchors {
top: flicker.top;
right: flicker.right;
bottom: flicker.bottom;
}
Rectangle {
id: handle;
height: (scrollbar.height * flicker.visibleArea.heightRatio);
color: "#5E5E5E";
border {
width: 1;
color: "white";
}
anchors {
left: parent.left;
right: parent.right;
}
Binding { // Calculate handle's x/y position based on the content position of the Flickable
target: handle;
property: "y";
value: (flicker.visibleArea.yPosition * scrollbar.height);
when: (!dragger.drag.active);
}
Binding { // Calculate Flickable content position based on the handle x/y position
target: flicker;
property: "contentY";
value: (handle.y / scrollbar.height * flicker.contentHeight);
when: (dragger.drag.active);
}
MouseArea {
id: dragger;
anchors.fill: parent;
drag {
target: handle;
minimumX: handle.x;
maximumX: handle.x;
minimumY: 0;
maximumY: (scrollbar.height - handle.height);
axis: Drag.YAxis;
}
}
}
}
Just use it like this :
Flickable {
id: myFlick;
}
ScrollBar {
flicker: myFlick;
}
It can be moved with mouse, and moves automatically when Flickable is scrolled.