Working on all things accessibility related and found that .accessibilityHidden(true) doesn't seem to work correctly. Even though VO doesn't read anything, it still shows the white box as you swipe around the page. The only way I've solved this is to put a VStack around the entire thing and then it seems to be fine, however it truncates the welcomeBodyText in simulator but not on a real device, which is worrying because I need to ensure that this works across all devices.
As the HeaderNav just shows the logo and company name, there is no reason to have it selectable, nor read out on every single page, so I wanted to completely hide it from VO and immediately jump to reading the welcomeHeaderText followed by the welcomeBodyText.
HeaderNav.swift
import SwiftUI
struct HeaderNav: View {
var body: some View {
VStack {
Spacer()
.frame(minHeight: 26, idealHeight: 26, maxHeight: 26)
.fixedSize()
HStack(spacing: 16) {
Spacer()
Image(decorative: "LogoHeader")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 70)
Text(LocalizationStrings.companyName)
.fontWeight(.light)
.foregroundColor(Color("WhiteText"))
.font(.system(size: 34))
.tracking(0.8)
Spacer()
} // End HStack
.accessibilityElement(children: .ignore)
.accessibilityLabel(LocalizationStrings.companyName)
} // End VStack
}
}
WelcomeTextView.swift
import SwiftUI
struct WelcomeTextView: View {
var body: some View {
Section {
VStack { // This is what needed to be added to make it work but causes issues in the simulator
HeaderNav()
.accessibilityHidden(true)
VStack(spacing: 10) {
Group {
HeaderText(text: LocalizationStrings.welcomeHeaderText)
BodyText(text: LocalizationStrings.welcomeBodyText)
} // End Group (Page Description)
.pageDescr()
} // End VStack
} // End VStack to make it work
.accessibilityElement(children: .combine)
} // End Section
.listRowBackground(Color("mainbkg"))
.listRowSeparator(.hidden)
}
}
pageDescr is a View Modifier that looks like:
struct PageDescr: ViewModifier {
func body(content: Content) -> some View {
VStack(alignment: .leading, spacing: 20) {
content
}
.padding(EdgeInsets(top: 5, leading: 32.0, bottom: 25, trailing: 32.0))
}
}
It was the top padding that was causing the issue, so I used a fixed size spacer in the HeaderNav above the closing } of the VStack instead and set the top padding to 0. Now it works.
Like this:
Spacer()
.frame(minHeight: 32, idealHeight: 32, maxHeight: 32)
.fixedSize()
Related
I'm trying to create a chat bubble like this:
Actual Bubble
Actual Bubble 2.0
This is what I have been able to achieve so far.
My attempt
My attempt
This is my code so far:
import SwiftUI
struct TestingView: View {
var body: some View {
ZStack {
/// header
VStack(alignment: .trailing) {
HStack {
HStack() {
Text("abcd")
}
HStack {
Text("~abcd")
}
}.padding([.trailing, .leading], 15)
.fixedSize(horizontal: false, vertical: true)
/// text
HStack {
Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")
}.padding([.leading, .trailing], 15)
/// timestamp
HStack(alignment: .center) {
Text("12:00 PM")
}.padding(.trailing,15)
}.background(Color.gray)
.padding(.leading, 15)
.frame(maxWidth: 250, alignment: .leading)
}
}
}
struct TestingView_Previews: PreviewProvider {
static var previews: some View {
TestingView()
}
}
The main goal is that I want the two labels on top to be distant relative to the size of the message content. I am not able to separate the two labels far apart i.e one should be on the leading edge of the bubble and the other one on the trailing edge.
Already tried spacer, it pushes them to the very edge, we need to apart them relative to the content size of the message as shown in attached images.
Here is a simplified code.
Regarding Spacer: To achieve your desired result you put both Text views inside of a HStack, and put a Spacer between them. So the Spacer pushes them apart to the leading and trailing edge.
Also I recommend to only use one padding on the surrounding stack.
VStack(alignment: .leading) {
// header
HStack {
Text("+123456")
.bold()
Spacer() // Spacer here!
Text("~abcd")
}
.foregroundStyle(.secondary)
// text
Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")
.padding(.vertical, 5)
// timestamp
Text("12:00 PM")
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding()
.background(Color.gray.opacity(0.5))
.cornerRadius(16)
.frame(maxWidth: 250, alignment: .leading)
}
We can put that header into overlay of main text, so it will be always aligned by size of related view, and then it is safe to add spacer, `cause it do not push label wider than main text.
Tested with Xcode 13.4 / iOS 15.5
var body: some View {
let padding: CGFloat = 15
ZStack {
/// header
VStack(alignment: .trailing) {
/// text
HStack {
//Text("Hello Everyone") // short test
Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!") // long test
}
.padding(.top, padding * 2)
.overlay(
HStack { // << here !!
HStack() {
Text("abcd")
}
Spacer()
HStack {
Text("~abcd")
}
}
, alignment: .top)
.padding([.trailing, .leading], padding)
/// timestamp
HStack(alignment: .center) {
Text("12:00 PM")
}.padding(.trailing, padding)
}.background(Color.gray)
.padding(.leading, padding)
.frame(maxWidth: 250, alignment: .leading)
}
}
To separate two components with fairly space in the middle, use HStack{} with Spacer().
This is a sample approach for this case. Code is below the image:
VStack {
HStack {
Text("+92 301 8226")
.foregroundColor(.red)
Spacer()
Text("~Usman")
.foregroundColor(.gray)
}
.padding(.bottom, 5)
.padding(.horizontal, 5)
Text("Testing testingtesting testing testing testingtesting testing testing testing testing testing testing testing testing testing.")
.padding(.horizontal, 5)
HStack {
Spacer()
Text("2:57 AM")
.foregroundColor(.gray)
.font(.subheadline)
}
.padding(.trailing, 5)
}
.frame(width: 300, height: 160)
.background(.white)
.cornerRadius(15)
I wanted some extra space on the top of the list so I tried using Spacer within the list and added modifiers to it. However I am not seeing the height getting reduced further. Below is the code for my view.
CustomView:
import SwiftUI
struct CustomView: View {
var body: some View {
VStack {
List {
Spacer()
.frame(minHeight: 1, idealHeight: 1, maxHeight: 2)
.fixedSize().listRowBackground(Color.clear)
UserLoginDetailsRowView().padding(.init(top: 0, leading: 5, bottom: 5, trailing: 5))
ForEach(1..<2) { _ in
VStack(alignment: .leading) {
Text("App version").fixedSize(horizontal: false, vertical: true).font(.headline).foregroundColor(.white)
Text("1.1.0").fixedSize(horizontal: false, vertical: true).font(.subheadline).foregroundColor(.white)
Spacer()
}.padding(.bottom, 15)
}.listRowBackground(Color.clear)
}
}.navigationBarTitle("Main Menu")
}
}
UserLoginDetailsRowView code:
import SwiftUI
struct UserLoginDetailsRowView: View {
var body: some View {
GeometryReader { geometry in
VStack(alignment: .center) {
Spacer()
Spacer()
Text("User's full name").lineLimit(2).font(.headline)
Text("Username").lineLimit(2).font(.subheadline)
Spacer()
}
ZStack {
Image("user-gray")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 30 , height: 30)
.offset(x: geometry.size.width / 2.8, y: -geometry.size.height/4)
}
}.frame(minHeight: 60.0)
}
}
This is how it looks with this code:
Regardless of the changes I make to minHeight, idealHeight and maxHeight in Spacer() within CustomView the result remains the same. However I want half of the space of what it's currently showing. I even tried replacing Spacer() with VStack and setting a frame height modifier to it, but at minimum, I do always see this much of space. I want the space reduced to half.
If I remove the Spacer() from CustomView then the image on my custom row gets chopped off and looks something like this. How do I reduce the space to half of what it is now?
Adding playground source code:
import SwiftUI
import PlaygroundSupport
struct CustomView: View {
var body: some View {
VStack {
Spacer().frame(minHeight: 25, idealHeight: 25, maxHeight: 30).fixedSize().listRowBackground(Color.clear)
List {
// Extra space for the top half of user icon within UserLoginDetailsRowView.
// Spacer().frame(minHeight: 25, idealHeight: 25, maxHeight: 30).fixedSize().listRowBackground(Color.clear)
UserLoginDetailsRowView().padding(.init(top: 0, leading: 5, bottom: 5, trailing: 5))
ForEach(1..<2) { _ in
VStack(alignment: .leading) {
Text("App Version").fixedSize(horizontal: false, vertical: true).font(.headline).foregroundColor(.white)
Text("1.1.0").fixedSize(horizontal: false, vertical: true).font(.subheadline).foregroundColor(.white)
Spacer()
}.padding(.bottom, 15)
}.listRowBackground(Color.clear)
}
}.navigationBarTitle("Back")
}
}
struct UserLoginDetailsRowView: View {
var body: some View {
GeometryReader { geometry in
VStack(alignment: .center) {
Spacer()
Spacer()
Text("User's full name").lineLimit(2).font(.headline)
Text("Username").lineLimit(2).font(.subheadline)
Spacer()
}
ZStack {
Image(systemName: "person.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 22 , height: 22)
.offset(x: geometry.size.width / 2.8, y: -geometry.size.height/4)
}
}.frame(minHeight: 60.0)
}
}
PlaygroundPage.current.setLiveView(CustomView())
Solution
The primary gap comes from the list style itself. if you apply .listStyle(PlainListStyle()) to the List it will reduce it to what you are looking for.
List { ... }.listStyle(PlainListStyle())
If you want to further reduce it and control it to the last pixel apply a .onAppear modifier to the list and set the content inset to your desired value.
List { .... }.onAppear(perform: {
UITableView.appearance().contentInset.top = -60
})
In the above code the value 60 is arbitrary in nature and you need to play around to get a value that fits your UI.
Explanation
The List default style adds a larger header which creates the spacing you were having issues with, this behaviour is similar to GroupedListStyle. From the documentation
On iOS, the grouped list style displays a larger header and footer than the plain style, which visually distances the members of different sections.
You can play around with other List Styles from the documentation to fit your needs better.
Full Playground Code - For .onAppear solution
import SwiftUI
import PlaygroundSupport
struct CustomView: View {
var body: some View {
VStack(alignment:.leading, spacing:0) {
List {
// Extra space for the top half of user icon within UserLoginDetailsRowView.
Spacer().frame(minHeight: 1, idealHeight: 1, maxHeight: 2)
.fixedSize().listRowBackground(Color.clear)
UserLoginDetailsRowView().padding(.init(top: 0, leading: 5, bottom: 5, trailing: 5))
ForEach(1..<2) { _ in
VStack(alignment: .leading) {
Text("App Version").fixedSize(horizontal: false, vertical: true).font(.headline).foregroundColor(.white)
Text("1.1.0").fixedSize(horizontal: false, vertical: true).font(.subheadline).foregroundColor(.white)
Spacer()
}.padding(.bottom, 15)
}.listRowBackground(Color.clear)
}.onAppear(perform: {
UITableView.appearance().contentInset.top = -60
})
}.navigationBarTitle("Back")
}
}
struct UserLoginDetailsRowView: View {
var body: some View {
GeometryReader { geometry in
VStack(alignment: .center) {
Spacer()
Spacer()
Text("User's full name").lineLimit(2).font(.headline)
Text("Username").lineLimit(2).font(.subheadline)
Spacer()
}
ZStack {
Image(systemName: "person.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 22 , height: 22)
.offset(x: geometry.size.width / 2.8, y: -geometry.size.height/4)
}
}.frame(minHeight: 60.0)
}
}
PlaygroundPage.current.setLiveView(CustomView())
I am trying to make an adaptive CommentViewRow for a social app where the whole comment text can be displayed within the row.
So far I am achieving this but I have 3 issues:
1 When the comment-text is short it is being centred within the row even when I specify ".alignment: .leading" in the VStack.
2 When the comment-text uses more than one line there is a mysterious padding between the user's profile picture & the comment-text?? see image below.
3 I am not sure if my .frame modifier is the best way to achieve what I am doing, it seems mickey-mouse, I was reading about .frame(idealWith, idealHeight, etc..) and not sure if that would help.
Any idea on how I can fix this so that each CommentViewRow displays like your average social-media comment view??
Thank you!
struct CommentViewRow: View {
var comment: Comment
var body: some View {
HStack {
KFImage("profilePicture")
// COMMENT
VStack(alignment: .leading, spacing: 5) {
Text("**\(comment.username)** \(comment.comment)")
.font(.caption)
.frame(width: 310)
.fixedSize(horizontal: true, vertical: false)
Text(comment.createdAt.timeAgoDisplay())
.bold()
.font(.caption)
}
Spacer()
}.padding([.leading, .trailing], 10)
}
}
1st option: If you really need that view to be 310 wide
You can change .frame(width: 310) to .frame(width: 310, alignment: .leading)
2nd option: Let the view adjust itself based on content, you just need to specify the alignment (.leading in this case)
struct CommentViewRow: View {
var comment: Comment
var body: some View {
HStack {
KFImage("profilePicture")
VStack(alignment: .leading, spacing: 5) {
Text("**\(comment.username)** \(comment.comment)")
.font(.caption)
Text(comment.createdAt.timeAgoDisplay())
.font(.caption.bold())
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding([.horizontal], 10)
}
}
yes, get rid of the frame:
struct ContentView: View {
var comment = "Thjfhg jhfgjhdfg jdfhgj dfhdfsjjdfgh djdshfg hjdfgjfdh ghjkf gdhjdfgh jkh fjg dfjkhgj dfglkhdfsg"
var body: some View {
HStack {
Image(systemName: "person.circle")
.font(.largeTitle)
VStack(alignment: .leading, spacing: 5) {
Text("\(comment)")
.font(.caption)
Text("3 minutes ago")
.bold()
.font(.caption)
}
Spacer()
}.padding([.leading, .trailing], 10)
}
}
My first ever question here at Stack Overflow.
I'm writing a small application for iOS and macOS. Text entry is done via (now) a TextField and a Button. The issue with the TextField is that it's a single line and doesn't allow for multiline text entry. So, I tried using TextEditor instead, but I can either set it up to not grow as more text is added, or it shows up very big to begin with.
What I'm saying is that ideally, it would mimic the behavior that the text entry in iMessage has: starts as the same size of a TextField but grows if needed to accommodate a multiline text like a TextEditor.
Here's the code I am using for this view:
var inputView: some View {
HStack {
ZStack {
//tried this here...
//TextEditor(text: $taskText)
TextField("New entry...", text: $taskText, onCommit: { didTapAddTask() })
.frame(maxHeight: 35)
.padding(EdgeInsets(top: 0, leading: 12, bottom: 0, trailing: 0))
.clipped()
.accentColor(.black)
.cornerRadius(8)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text(taskText).opacity(0).padding(.all, 8)
}
Button(action: AddNewEntry, label: { Image(systemName: "plus.circle")
.imageScale(.large)
.foregroundColor(.primary)
.font(.title) }).padding(15).foregroundColor(.primary)
}
}
Any way of doing this?
I tried different approaches found in different questions from other users, but I can't quite figure out.
Here's how it looks:
How the TextEdit looks
I also have tried something like this and played with different values for the .frame:
TextEditor(text: $taskText)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 200)
.border(Color.primary, width: 1)
.padding(EdgeInsets(top: 0, leading: 12, bottom: 0, trailing: 0))
Any help is appreciated.
Thanks.
Oh, and I'm using Xcode 12.5.1 and target is iOS 14.x and macOS Big Sur for now.
EDIT to answer jnpdx.
When I add the code from Dynamic TextEditor overlapping with other views this is how it looks, and it does not change dynamically.
How it looks when the app launches
How it looks when you type text
Here's an example, using your original code with the Button next to the TextEditor. The TextEditor grows until it hits the limit, defined by maxHeight. It also has a view for the messages (since you mentioned iMessage), but you could easily remove that.
struct ContentView: View {
#State private var textEditorHeight : CGFloat = 100
#State private var text = "Testing text. Hit a few returns to see what happens"
private var maxHeight : CGFloat = 250
var body: some View {
VStack {
VStack {
Text("Messages")
Spacer()
}
Divider()
HStack {
ZStack(alignment: .leading) {
Text(text)
.font(.system(.body))
.foregroundColor(.clear)
.padding(14)
.background(GeometryReader {
Color.clear.preference(key: ViewHeightKey.self,
value: $0.frame(in: .local).size.height)
})
TextEditor(text: $text)
.font(.system(.body))
.padding(6)
.frame(height: min(textEditorHeight, maxHeight))
.background(Color.black)
}
.padding(20)
Button(action: {}) {
Image(systemName: "plus.circle")
.imageScale(.large)
.foregroundColor(.primary)
.font(.title)
}.padding(15).foregroundColor(.primary)
}.onPreferenceChange(ViewHeightKey.self) { textEditorHeight = $0 }
}
}
}
struct ViewHeightKey: PreferenceKey {
static var defaultValue: CGFloat { 0 }
static func reduce(value: inout Value, nextValue: () -> Value) {
value = value + nextValue()
}
}
I am currently creating a content view for my application and am experiencing some strange behavior with padding. As seen in the photo below, there is quite a bit of space below the navigation bar at the top of the phone. I don't specify any padding here so I'm wondering why there is so much space between the top and where the image is displayed. The image doesn't have that large of a white box around it either.
My code does not specify any kind of margin or padding. I'm new to Swift and SwiftUI so I'm curious if there is some automatic padding applied to navigation views?
import Kingfisher
struct BottleView: View {
let bottle: Bottle
var body: some View {
VStack {
KFImage(URL(string: bottle.image ?? "")!)
.resizable()
.frame(width: 128, height: 256)
VStack(alignment: .leading) {
HStack {
Text(bottle.name)
.font(.title)
Spacer()
Text("Price")
}
HStack {
Text(bottle.varietal ?? "")
Spacer()
Text("$\(bottle.price ?? "")")
}
.font(.subheadline)
.foregroundColor(.secondary)
VStack(alignment: .leading) {
Text("Information")
.font(.title2)
Text(bottle.information ?? "")
}
}
}
}
}
If you apply a .background(Color.red) to the VStack, you'll see that it's centered in the screen.
var body: some View {
VStack {
Image("TestImage")
.resizable()
.frame(width: 128, height: 256)
/// ... more code
}
.background(Color.red)
}
This is because, by default, most SwiftUI views are centered. For example, try just a Text:
struct ContentView: View {
var body: some View {
Text("Hello, I'm centered!")
}
}
So if you don't want it centered, this is where Spacers come in. These expand to fill all available space, pushing all other views. Here's the code that gets rid of the "bit of space below the navigation bar at the top of the phone":
(note that I replaced your Bottle properties with static text, make sure you change them back)
struct BottleView: View {
// let bottle: Bottle
var body: some View {
VStack {
Image("TestImage")
.resizable()
.frame(width: 128, height: 256)
VStack(alignment: .leading) {
HStack {
Text("Blantons")
.font(.title)
Spacer()
Text("Price")
}
HStack {
Text("Bourbon")
Spacer()
Text("$59.99")
}
.font(.subheadline)
.foregroundColor(.secondary)
VStack(alignment: .leading) {
Text("Information")
.font(.title2)
Text("Product info here")
}
}
Spacer() /// spacer right here! pushes the other views up
}
.background(Color.red)
.navigationBarTitleDisplayMode(.inline) /// get rid of the additional top gap that the default Large Title navigation bar produces
}
}
Result: