SwiftUI Picker Label with PickerStyle .menu in iOS HowTo - ios

For some reason Apple decided to drop Label support for Pickers
(tested in iOS15 and iOS16)
For example:
Picker(selection: $gender,
label:
"Select your gender"
, content: {
Text(Gender.male.rawValue).tag(Gender.male)
Text(Gender.female.rawValue).tag(Gender.female)
Text(Gender.nobinary.rawValue).tag(Gender.nobinary)
}).pickerStyle(.automatic)
.font(.largeTitle)
.accentColor(.white)
ignores the label view.
So howto solve that?

To add a Label View out of the box without custom View one has to use Picker in Menu View embedded.
Now one can use modifier on the Menu Label Views and even use logic for the selected text.
Menu {
Picker(selection: $gender,
label: EmptyView(),
content: {
Text(Gender.male.rawValue).tag(Gender.male)
Text(Gender.female.rawValue).tag(Gender.female)
Text(Gender.nobinary.rawValue).tag(Gender.nobinary)
}).pickerStyle(.automatic)
.accentColor(.white)
} label: {
Text(gender == .unselected ? "Select your gender" : gender.rawValue)
.font(.title3)
.frame(maxWidth: .infinity)
.frame(height: 55)
.background(.white)
.cornerRadius(10)
.accentColor(.pink)
}

Related

SwiftUI Button Disable styling does not work in some cases

I have the following button in a custom view that I reuse in multiple places
Button(action: { selectedDate = date }) {
VStack {
Text(day.shortName)
.font(.caption2)
.foregroundColor(isSelectedDate ? .white : .primary)
.frame(maxWidth: .infinity)
Spacer().frame(height: 7)
Text("\(date.dayOfMonth)")
.bold()
.foregroundColor(isSelectedDate ? .white : .primary)
.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.purple.brightness(isSelectedDate ? 0 : 0.6))
.clipped()
}.disabled(isInPast)
Dates in the past supposed to be disabled, and I confirmed that they are actually disabled as expected; however, the disabled styling looks different in multiple screens although it's the exact same view being used.
What could cause the disable state to not be styled accordingly in some screens?
In both screenshots dates from 25-29 are disabled
In both usages I simply add the view to a VStack
var body: some View {
VStack {
WeekView(selectedDate: $booking.selectedDate).padding()
var body: some View {
VStack(spacing: 0) {
WeekView(selectedDate: $selectedDate)
.padding(.horizontal)
.padding(.bottom)
Don't rely on primary color. Use a custom color and use isInPast to make an opacity.
Figured it out, the parent in one of the screens had .buttonStyle(.plain) which makes the disabled styling work as expected. So I just dded that to the component itself to make sure the disabled styling is always in place

SwiftUI - can I make one element in Form fill the whole screen width (without horizontal margins)?

I would like a single item inside SwiftUI Form to run from side to side, without having Form's default margins.
Unfortunately, whatever I do (like ading a wider .frame, negative horizontal padding, or .offset), the team image view seems to be always cropped by the form to fit the form area (= has horizontal margins).
Is it possible to make the Image below touch the left and right side of the screen?
I am using Form for my app settings, but I would like to add a full-width section there (think eg. a banner to promote a feature).
SwiftUI Playgrounds code:
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var body: some View {
Form {
Section(
header: Text("First section")
) {
Text("Hello world")
}
Text("The image below should be stretched to touch the left and right window edge, without being cropped by the Form.")
Image(systemName: "sun.max.fill")
.resizable()
.aspectRatio(contentMode: .fill)
.listRowInsets(EdgeInsets()) // this is supposed to fix the problem, but all it does is to set the default item inner padding to zero, so the image at least touches the edge of teal area.
.listRowBackground(Color.teal)
Section(
header: Text("Last section")
) {
Text("Hello world")
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())
How it looks:
Unfortunately, SwiftUI Form is very temperamental and forces you to strictly adhere to the standard iOS Settings screen formatting.
Fortunately, you can re-implement similar formatting yourself with SwiftUI!
For the top, something like:
VStack(spacing: 4) {
Text("FIRST SECTION")
.font(.system(size: 12, weight: .regular))
.foregroundColor(.gray)
.padding(.leading)
Text("Hello, world!")
.font(.system(size: 15, weight: .regular))
.foregroundColor(.black)
.padding(.horizontal)
.frame(height: 44, alignment: .center)
.background(Color.white)
.cornerRadius(10)
}

Add View in navigationBarTitle - SwiftUI

I am able to add Title using .navigationBarTitle(Text((msgDetails.name))) But i wanted to add subtitle under the title in the navigationbar. Looks like title will not accept the View and it accepts only Text. I tried \n in the title but it is not working. IS there any way i can add the subtitle in navigation bar. I used leading and trailing to add left and right button in the navigation bar. I wanted to show title and subtitle along with this left and right button
Navigation Bar
If you look in SwiftUI documentation you'll see only a few overloads of navigationBarTitle function. All of them requires special parameters, like Text or StringProtocol. So you can't just put some View into navigation bar.
I can propose one strange, but working version. It's about using .navigationBarItems(leading:... - it requires some view, which you can customize (within reason). Here is simple example:
struct ContentView: View {
var body: some View {
NavigationView {
Text("Main view")
.navigationBarItems(leading:
HStack {
Button(action: {}) {
Image(systemName: "return")
}
VStack {
Text("Title")
.bold()
.font(.system(size: 30))
Text("Subtitle")
.italic()
.font(.system(size: 15))
}
.padding(.horizontal, 100) // mb it's better to use GeometryReader for centering
})
}
}
}
and you'll achieve something like this:

How to show a view when tapping on a list item?

I am working with a list in SwiftUI, I am attempting to recreate a system I had with TableView whereby a user can tap a cell and then a new view is presented with data relating to said cell. Now we have lists my code has changed to the following:
List {
ForEach(clients, id: \.id) { client in
VStack(alignment: .center) {
HStack{
Text(client.firstName ?? "Unknown" + " ")
.font(.system(size: 17))
.foregroundColor(Color.init(hex: "47535B"))
.fontWeight(.medium)
.multilineTextAlignment(.leading)
.padding(.leading)
Text(client.lastName ?? "Unknown")
.font(.system(size: 17))
.foregroundColor(Color.init(hex: "47535B"))
.fontWeight(.medium)
.multilineTextAlignment(.leading)
Spacer()
}
}
.frame(height: 50.0)
.background(Color.init(hex: "F6F6F6"))
.cornerRadius(7.0)
}
}
.padding(.horizontal, 3.0)
.padding(.vertical, 115.0)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
I realise I can use a NavigationLink and place the entire thing into a NavigationView but this functionality is not what I want, below is an image of my interface. What I am trying to achieve is when the user taps a cell it presents the data in the space on the right where it says "Select a client to view their profile". With the NavigationView setup I can only use the 2 default styles neither of which are suitable for me since I cannot customise where the navigation view gets placed. Is there a way I can register the same tap but have my own custom system for displaying the resulting data where I want in my interface? Perhaps I am wrong about NavigationView or maybe there is a way to have the NavigationView be positioned entirely outside of the view that contains the item list?
If you don't want to or aren't using use a NavigationView, then you likely have both the client list and the client detail in the same view somewhere. I would try adding #State private var selectedClient: Client? = nil to whatever view has both the list and the detail.
First, pass selectedClient as a binding to the list. Next, whenever one of the list items is tapped (achievable through .onTapGesture() or Button), Update selectedClient.
In your detail view, accept a bindable Client? parameter. If it's nil, then just show your current Text view. If it's not nil, then build the detail UI.
Hope this helps!

Avoid button styling its content in SwiftUI

I'm creating an iOS app using Apple's SwiftUI framework. As I need to detect if the user taps on a specific area of the screen, I obviously use a button.
The problem is that the area contains an Image and a Text, and as the button automatically gives its content the blue color, the image is also colored, so instead of being an Image it's just a blue rounded rectangle.
It is said that an image is worth a thousand words, and as I'm not good at explaining, here you have a graphic demonstration of what happens:
Outside the button (without button styling)
Inside the button (with button styling)
This happens because the button is adding .foregroundColor(.blue) to the image.
How can I avoid/disable the button adding style to its components?
EDIT: This is my button code:
ContentView.swift:
Button(action: {/* other code */}) {
PackageManagerRow(packageManager: packageManagersData[0])
}
PackageManagerRow.swift:
struct PackageManagerRow : View {
var packageManager : PackageManager
var body: some View {
VStack {
HStack {
Image(packageManager.imageName)
.resizable()
.frame(width: 42.0, height: 42.0)
Text(verbatim: packageManager.name)
Spacer()
Image(systemName: "checkmark")
.foregroundColor(.blue)
.opacity(0)
}.padding(.bottom, 0)
Divider()
.padding(.top, -3)
}
}
}
I think this is from the rendering mode for the image you are using.
Where you have Image("Cydia logo") (or whatever).
You should be setting the rendering mode like...
Image("Cydia Logo").renderingMode(.original)
You can also add a PlainButtonStyle() to your button to avoid iOS style behaviors.
Something like that with your example :
Button(action: {/* other code */}) {
PackageManagerRow(packageManager: packageManagersData[0])
}.buttonStyle(PlainButtonStyle())
I hope it will help you!
Another option is to not use a Button wrapper, but instead use tapAction directly on the Image to trigger your action when the image is pressed
HStack {
Button(action: {
print("Tapped")
}, label: {
Image("Logo").renderingMode(.original) // Add Rendering Mode
})
Text("Cydia")
}
A button with an icon! How original 😀.
If you are dealing with SF symbols then the following will do fine:
Button(action: addItem) {
Text(Image(systemName: "plus").renderingMode(.original))
+
Text("This is Plus")
}
.font(.system(size: 42))
The limitation of the option above is you don't have control over Image's size. So for custom images the following is more appropriate:
Button(action: addItem) {
Label(
title: { Text("Label").font(.system(size: 40)) }, // Any font you like
icon: { Image(systemName: "rectangle.and.pencil.and.ellipsis") // Both custom and system images, i.e. `Image("Cydia logo")`
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 42, height: 42) // Any size you like
.padding() // Any padding you need
} // and etc.
)
}
Apply the style .plain to your button to avoid overlay color.
// Before
Button(...)
// After
Button(...)
.buttonStyle(.plain) // Remove the overlay color (blue) for images inside Button
.plain button style, that doesn’t style or decorate its content while idle, but may apply a visual effect to indicate the pressed, focused, or enabled state of the button.
Another solution is to custom the style with ButtonStyle
like: struct MyButtonStyle:ButtonStyle { }
You have to render the original image by adding .renderingMode(.original) right after your image declaration.
Image("your_image_name")
.renderingMode(.original)

Resources