Here's a minimal, reproducible example of what I want to do.
I have an array of paragraphs.
var notes = [
"One line paragraph",
"This is a small paragraph. This is a small paragraph. This is a small paragraph. This is a small paragraph.",
"This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph."
]
This is how I want to display this:
Here's my code.
struct ContentView: View {
var notes = [
"One line paragraph",
"This is a small paragraph. This is a small paragraph. This is a small paragraph. This is a small paragraph.",
"This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph."
]
var body: some View {
VStack(alignment: .leading) {
ForEach(self.notes, id: \.self) {note in
HStack {
Capsule()
.fill(Color.blue)
.frame(width: 4.5)
Text(note)
.lineLimit(nil)
}
.padding()
}
}
}
}
This is the output I got:
I even tried adding a Spacer() to the bottom of the VStack (after the ForEach) but the output is still same.
What I want to know is how to change the height of those blue vertical bars to the height of their respective paragraphs like in the first screenshot.
Here is possible approach. Tested with Xcode 11.4 / iOS 13.4
var body: some View {
VStack(alignment: .leading) {
ForEach(self.notes, id: \.self) {note in
HStack {
Text(note)
.padding(.leading)
}
.overlay(Capsule() // also can be .background
.fill(Color.blue)
.frame(width: 4.5), alignment: .leading)
.padding()
}
}
}
Related
I want to create a complication rendered by a SwiftUI View that contains a label and a timer value.
I want the label to be on the complication background layer, and the timer value to be on the complication foreground layer so that they get tinted separately.
I would like this line of text, comprised of 2 parts, to be centered.
The trouble is, when using Text.DateStyle.timer, the Text behaves differently within a complication vs in a normal view.
In a normal view the Text frame behaves as any other text, only taking the space it needs.
When displayed in a complication, the Text frame expands to fill all the space it can, and the text within is left aligned.
This makes it so I cannot find a way to center the group of 2 Texts.
I tried a somewhat hacky approach with infinite spacers to try to steal the extra space from the Text that has the expanding frame. This works to center the content, but it causes the Text to truncate.
HStack {
Text("T:")
.foregroundColor(.accentColor)
Text(Date(), style: .timer)
.complicationForeground()
}
HStack {
Spacer()
.frame(maxWidth: .infinity)
HStack {
Text("T:")
.foregroundColor(.accentColor)
Text(Date(), style: .timer)
.complicationForeground()
}
Spacer()
.frame(maxWidth: .infinity)
}
A normal preview:
A preview of rendering within complication:
CLKComplicationTemplateGraphicExtraLargeCircularView(
ExtraLargeStack()
)
.previewContext(faceColor: .multicolor)
Edit to show full code
import ClockKit
import SwiftUI
struct ExtraLargeStack: View {
var body: some View {
VStack(alignment: .center) {
HStack {
Text("T:")
.foregroundColor(.accentColor)
Text(Date(), style: .timer)
.complicationForeground()
}
HStack {
Spacer()
.frame(maxWidth: .infinity)
HStack {
Text("T:")
.foregroundColor(.accentColor)
Text(Date(), style: .timer)
.complicationForeground()
}
Spacer()
.frame(maxWidth: .infinity)
}
}
.font(.system(size: 18, weight: .regular))
.lineLimit(1)
}
}
struct ExtraLargeStack_Previews: PreviewProvider {
static var previews: some View {
/// Preview normal view
// ExtraLargeStack()
/// Preview as Complication
CLKComplicationTemplateGraphicExtraLargeCircularView(
ExtraLargeStack()
)
.previewContext(faceColor: .multicolor)
}
}
Edit: Another partial solution
Based on suggestions from #Yrb, an overlay provides a partial solution that may be good enough for my use case.
The following does not fully center the 2 part line, but it is pretty close.
HStack {
// Use placeholder text to create a view with the appropriate size for _most_ timer values that I need to support
Text("L: 00:00 ").hidden()
}
.overlay(
// overlay the real content, which is constrained to the frame created by the hidden placeholder.
HStack(spacing: 5) {
Text("L:")
.foregroundColor(.accentColor)
Text(Date() - 3599, style: .timer)
.complicationForeground()
}
)
So, I figured out what the issue with aligning Text(Date(), style: .timer) is. The timer format from hours on down. The document give this as an example: 2:59 36:59:01. It appears that .timer reserves all of the possible space it needs and then is formatted on that possible space, not the space actually used. There does not appear to be any way to change this behavior, even if your goal is a 5 minute countdown timer.
I think you need to consider slight UI change. I did find that you can change the alignment of the displayed Text with a .timer by using .multilineTextAlignment(), but that is about all you can do. The following code demonstrates this:
struct ExtraLargeStack: View {
var body: some View {
// I removed (alignment: .center) as it is redundant. VStacks default to center
VStack {
// I put the negative spacing to tighten the T: with the timer
VStack(spacing: -6) {
Text("T:")
.foregroundColor(.accentColor)
Text(Date(), style: .timer)
// If you center with .multilineTextAlignment the timer
// will be centered
.multilineTextAlignment(.center)
.complicationForeground()
}
HStack {
HStack {
Text(Date(), style: .timer)
.multilineTextAlignment(.center)
.complicationForeground()
.overlay(
Text("T:")
.foregroundColor(.accentColor)
// This offset would need to be computed
.offset(x: -30, y: 0)
)
}
}
}
.font(.system(size: 18, weight: .regular))
}
}
I left the second timer as an HStack, but I put your Text("T") as an .overlay() with a .offset(). I don't particularly like this as it will be fragile if you attempt to adjust the offset for the additional time units, but if you have a limited range, it may work well enough. Also, if you use .monospaced on the timer text, the computation should be a linear amount.
As you can see from the image below the L (Lorem) and the p (previewing) are cutoff, any idea why some of the text inside the Text gets cut off?
struct ContentView: View {
var body: some View {
ZStack {
Image("placeholder-image")
.resizable()
.scaledToFill()
.ignoresSafeArea()
VStack {
Text("Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups..")
.foregroundColor(Color.systemGray)
.cornerRadius(15)
Button("Tap Me") {
// some action
}.buttonStyle(.borderedProminent)
}
.padding()
.background(.thinMaterial)
.cornerRadius(15)
}
}
}
The cornerRadius adds clipping, so remove it after text (anyway it is not needed there by logic of your code even if it would behave differently)
VStack {
Text("Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups..")
.foregroundColor(Color.systemGray)
//.cornerRadius(15) // << this !!
you can use as below for text:
.fixedSize(horizontal: false, vertical: true)
I need precise control over the area taken by Text. I created the most basic program that shows unexpected top and bottom spacing being added to a text. Where is this extra padding coming from? How to get rid of it?
#main
struct myApp: App {
init() { }
var body: some Scene {
WindowGroup {
Text("80")
.font(.system(size: 30, weight: .bold, design: .default))
.background(Color.red)
}
}
}
Text seems to have default padding as seen here
You can get past that by adjusting the padding to a negative amount
Replace your code with this
Text("80")
.font(.system(size: 30, weight: .bold, design: .default))
.padding(.vertical, -6)
.background(Color.red)
Here is a solution if you want to make it dynamic
struct TestView: View {
var fontSize: CGFloat = 110
var paddingSize: CGFloat {
-(fontSize * 0.23)
}
var body: some View {
Text("80")
.font(.system(size: fontSize, weight: .bold, design: .default))
.padding(.vertical, paddingSize)
.background(Color.red)
Text("Hello")
}
}
So even with a large font size of 110 like in the picture you can render it how you like
You'll need to tweak the multiplier how you see fit
Turns out that the padding top and bottom is actually not there at all. In my example with numbers this looks like wasted space, but actually certain characters do need this room as can be seen on this picture:
Since I am only going to show numbers I have used the solution by #Sergio to correct for this overspace.
I am developing a MacOS app using SwiftUI and would like a Picker to shrink to only show its label and content, and a Spacer to take up the rest of the view, but I'm not sure what the correct way to do this. The code looks something like this:
HStack{
Text("hello")
Text("more text")
Spacer()
Picker(selection: self.$stuff, label: Text("some stuff:")) {
ForEach(0 ..< self.getStuff().count) {
Text(self.getStuff()[$0])
}
}
}
and the Picker is expanded to take up as much room as possible. I would prefer that the picker take up the minimum amount of space and the Spacer to take up the remaining space.
Edit: photo:
You can use .scaledToFit to fit it to content as below
Picker(selection: self.$stuff, label: Text("some stuff:")) {
ForEach(0 ..< self.getStuff().count) {
Text(self.getStuff()[$0])
}
}
.scaledToFit()
// .frame(width: 160) // < alternate approach - give explicit desired width
Added on the 24th of July:
This line of code fixes the space in the detail view. However... in the list view the title has become a lot smaller too.
.navigationBarTitle(Text("Egg management"), displayMode: .inline)
Added on the 23th of July:
Thanks to the tips I made a lot of progress. Especially the tip to add borders does wonders. You see exactly what happens!
However, there seems to be a difference between the Xcode Preview canvas, the simulator and the physical device. Is this a bug because -after all- it is still beta? Or is there anything I can do?
As you can see in the images... only in the Xcode Preview canvas the view connects to the top of the screen.
I believe it has something to do with the tabbar. Since when I look at the Xcode Preview canvas with the tabbar... that space above is also there. Any idea how to get rid of that?
Original postings:
This is my code for a detailed list view:
import SwiftUI
struct ContentDetail : View {
#State var photo = true
var text = "Een kip ..."
var imageList = "Dag-3"
var day = "3.circle"
var date = "9 augustus 2019"
var imageDetail = "Day-3"
var weight = "35.48"
var body: some View {
VStack (alignment: .center, spacing: 10) {
Text(date)
.font(.title)
.fontWeight(.medium)
ZStack (alignment: .topLeading){
Image(photo ? imageDetail : imageList)
.resizable()
.aspectRatio(contentMode: .fit)
.background(Color.black)
.padding(.trailing, 0)
.tapAction {
self.photo.toggle() }
HStack {
Image(systemName: day)
.resizable()
.padding(.leading, 10)
.padding(.top, 10)
.frame(width: 40, height: 32)
.foregroundColor(.white)
Spacer()
Image(systemName: photo ? "photo" : "pencil.circle")
.resizable()
.padding(.trailing, 10)
.padding(.top, 10)
.frame(width: 32, height: 32)
.foregroundColor(.white)
}
}
Text(text)
.lineLimit(6)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 6)
} .padding(20)
}
}
#if DEBUG
struct ContentDetail_Previews : PreviewProvider {
static var previews: some View {
ContentDetail()
}
}
#endif
Also included is the preview canvas. What I don't get is how I can make sure the text and photo are aligned to the top (instead of the middle). I tried with Spacers, padding etc.
I must be overseeing something small I guess... but. Can somebody point me in the right direction? Thanks.
Added:
After both answers I added a Spacer() after the last text. In Xcode in the preview canvas everything looks okay now. But on my connected iPhone 7 Plus there are some problems: the view is not aligned to the top, and the image is cropped (icon on the right is gone; white banding to the right).
Adding a Spacer() after the last text shifts everything to the top. Tested on iPhone Xr simulator (not preview).
...
Text(text)
.lineLimit(6)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 6)
Spacer()
}
To remove the space at the top:
VStack {
...
}
.padding(20)
.navigationBarTitle("TITLE", displayMode: .inline)
Think in terms of what a Spacer() does. It "moves" the views as far apart as it can - at least, without a specific space.
So you have this:
VStack {
Text
ZStack {
Image
HStack {
Image
Spacer()
Image
}
}
Text
}
All told, going from inner to outer, you have a horizontal stack of two images placed as far apart (the spacer is between them) inside of a "Z axis" stack that places an image on top of them, inside of a vertical stack that has some text above it.
So if you want to move everything in that vertical stack to the top, you simply need to add one last spacer:
VStack {
Text
ZStack {
Image
HStack {
Image
Spacer()
Image
}
}
Text
Spacer() // <-- ADD THIS
}
Last note: Don't be afraid to adding additional "stacks" to your view. In terms of memory footprint, it's really just a single view with no performance hit.
EDIT: I took your original view and changed everything to placeholders...
var body: some View {
VStack (alignment: .center, spacing: 10) {
Text("Text #1")
.font(.title)
.fontWeight(.medium)
ZStack (alignment: .topLeading) {
Text( "Image #1")
HStack {
Text("Image #2")
Spacer()
Text("Image #3")
}
}
Text("Text #2")
.lineLimit(6)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.leading, 6)
} .padding(20)
}
As expected, everything is vertically centered. Adding a Spacer() below "Text #2" throws everything to the top. A couple of thoughts:
Starting there, and add in your Image views one by one. Add in the modifiers like that also.
I don't have the specific images you are rendering, so maybe put a noticeable background color on various things (orange is my personal favorite) and see if the top Image is actually on top but the image makes it appear as though it isn't. A border would work pretty well too.