Align views in Picker - swift

How do I align the Color views in a straight line with the text to the side?
To look like so (text aligned leading):
█  red
█  green
█  blue
Or this (text aligned center):
█    red
█  green
█   blue
Current code:
struct ContentView: View {
#State private var colorName: Colors = .red
var body: some View {
Picker("Select color", selection: $colorName) {
ForEach(Colors.allCases) { color in
HStack {
color.asColor.aspectRatio(contentMode: .fit)
Text(color.rawValue)
}
}
}
}
}
enum Colors: String, CaseIterable, Identifiable {
case red
case green
case blue
var id: String { rawValue }
var asColor: Color {
switch self {
case .red: return .red
case .green: return .green
case .blue: return .blue
}
}
}
Result (not aligned properly):
Without the Picker, I found it is possible to use alignmentGuide(_:computeValue:) to achieve the result. However, this needs to be in a Picker.
Attempt:
VStack(alignment: .custom) {
ForEach(Colors.allCases) { color in
HStack {
color.asColor.aspectRatio(contentMode: .fit)
.alignmentGuide(.custom) { d in
d[.leading]
}
Text(color.rawValue)
.frame(maxWidth: .infinity)
.fixedSize()
}
}
.frame(height: 50)
}
/* ... */
extension HorizontalAlignment {
struct CustomAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[HorizontalAlignment.leading]
}
}
static let custom = HorizontalAlignment(CustomAlignment.self)
}
Result of attempt:

Possible solution is to use dynamic width for labels applied by max calculated one using view preferences.
Here is a demo. Tested with Xcode 13beta / iOS15
Note: the ViewWidthKey is taken from my other answer https://stackoverflow.com/a/63253241/12299030
struct ContentView: View {
#State private var colorName: Colors = .red
#State private var maxWidth = CGFloat.zero
var body: some View {
Picker("Select color", selection: $colorName) {
ForEach(Colors.allCases) { color in
HStack {
color.asColor.aspectRatio(contentMode: .fit)
Text(color.rawValue)
}
.background(GeometryReader {
Color.clear.preference(key: ViewWidthKey.self,
value: $0.frame(in: .local).size.width)
})
.onPreferenceChange(ViewWidthKey.self) {
self.maxWidth = max($0, maxWidth)
}
.frame(minWidth: maxWidth, alignment: .leading)
}
}
}
}

I think this should align your text and fix your issue.
struct ContentView: View {
#State private var colorName: Colors = .red
var body: some View {
Picker("Select color", selection: $colorName) {
ForEach(Colors.allCases) { color in
HStack() {
color.asColor.aspectRatio(contentMode: .fit)
Text(color.rawValue)
.frame(width: 100, height: 30, alignment: .leading)
}
}
}
}
}
A simple .frame modifier will fix these issues, try to frame your text together or use a Label if you don't want to complicate things when it comes to pickers or list views.
If you do go forward with this solution try to experiment with the width and height based on your requirements, and see if you want .leading, or .trailing in the alignment

Related

How can I make a smoothed custom Picker on SwiftUI?

I would like to replicate this picker in swiftUI. In particular, I have a button on the bottom left of the screen and when I click it I would like to show different icons (similar to the image below, but vertically). As soon as I click on one of the choices the button should shrink back to the initial form (circle) with the chosen icon.
When closed:
When open:
I am new to this language and to app in general, I tried with a Pop Up menu, but it is not the desired result, for now I have an horizontal segmented Picker.
You can't do this with the built-in Picker, because it doesn't offer a style like that and PickerStyle doesn't let you create custom styles (as of the 2022 releases).
You can create your own implementation out of other SwiftUI views instead. Here's what my brief attempt looks like:
Here's the code:
enum SoundOption {
case none
case alertsOnly
case all
}
struct SoundOptionPicker: View {
#Binding var option: SoundOption
#State private var isExpanded = false
var body: some View {
HStack(spacing: 0) {
button(for: .none, label: "volume.slash")
.foregroundColor(.red)
button(for: .alertsOnly, label: "speaker.badge.exclamationmark")
.foregroundColor(.white)
button(for: .all, label: "volume.2")
.foregroundColor(.white)
}
.buttonStyle(.plain)
.background {
Capsule(style: .continuous).foregroundColor(.black)
}
}
#ViewBuilder
private func button(for option: SoundOption, label: String) -> some View {
Button {
withAnimation(.easeOut) {
if isExpanded {
self.option = option
isExpanded = false
} else {
isExpanded = true
}
}
} label: {
Image(systemName: label)
.fontWeight(.bold)
.padding(10)
}
.frame(width: shouldShow(option) ? buttonSize : 0, height: buttonSize)
.opacity(shouldShow(option) ? 1 : 0)
.clipped()
}
private var buttonSize: CGFloat { 44 }
private func shouldShow(_ option: SoundOption) -> Bool {
return isExpanded || option == self.option
}
}
struct ContentView: View {
#State var option = SoundOption.none
var body: some View {
ZStack {
Color(hue: 0.6, saturation: 1, brightness: 0.2)
SoundOptionPicker(option: $option)
.shadow(color: .gray, radius: 3)
.frame(width: 200, alignment: .trailing)
}
}
}

NavigationLink don't navigate anymore after incomplete swipe from left to right

In my app I have a NavigationStack inside the detail of a NavigationSplitView. With the code below the navigation back and forward works fine but if from the detail, I incompletely swipe left to dismiss the view, the NavigationLink doesn't work anymore. This code is partially copied from Apple Documentation.
Does anyone know what causes the problem?
struct ContentView: View {
let colors: [Color] = [.purple, .pink, .orange]
#State private var selection: Color? = nil
var body: some View {
NavigationSplitView {
List(colors, id: \.self, selection: $selection) { color in
NavigationLink(color.description, value: color)
}
} detail: {
NavigationStack {
if let color = selection {
VStack {
NavigationLink(color.description, value: color)
}
.navigationDestination(for: Color.self) { color in
RoundedRectangle(cornerRadius: 10)
.fill(color)
.frame(width: 150, height: 150)
}
} else {
Text("Pick a color")
}
}
}
}
}
EDIT:
I've made some code improvements creating separate struct for each view to avoid confusion and better understand the code but the problem persist.
struct ContentView: View {
let colors: [Color] = [.purple, .pink, .orange]
#State private var selection: Color? = nil
var body: some View {
NavigationSplitView {
List(colors, id: \.self, selection: $selection) { color in
NavigationLink(color.description, value: color)
}
} detail: {
NavigationStack {
if let color = selection {
DetailView(color: color)
} else {
Text("Pick a color")
}
}
}
}
}
struct DetailView: View {
let color: Color
var body: some View {
VStack {
NavigationLink("Go to third view", value: color)
.padding()
.background(color)
.foregroundColor(.white)
}
.navigationTitle("Detail View")
.navigationDestination(for: Color.self) { color in
ThirdView(color: color)
}
}
}
struct ThirdView: View {
let color: Color
var body: some View {
RoundedRectangle(cornerRadius: 10)
.fill(color)
.frame(width: 150, height: 150)
.navigationTitle("Third View")
}
}
It looks like the bug is fixed. At least it works as expected on the latest Xcode 14.1 RC.

SwiftUI and CoreData: Horizontal bar chart with different coloured values

I am learning SwiftUI with CoreData and I have that one demo app where I am stuck.
Outcome:
I would like to present different coloured bar charts based on numeral values (calories). I managed to present numeral values with one colour, but not different colours based on value.
Here is image about desired outcome and my Swift code.
Thank you for any help! -Toni
Desired UI outcome
Code screenshot
import SwiftUI
struct ColourChart: View {
#Environment(\.managedObjectContext) var managedObjContext
#State private var name = ""
#State private var calories: Double = 0
#State private var color: Color = .gray
#FetchRequest(sortDescriptors: [SortDescriptor(\.calories)]) var food: FetchedResults<CaloriesEntity>
var body: some View {
List {
ForEach(food) { food in
VStack(alignment: .leading) {
HStack(alignment: .top) {
Text(food.name ?? "Unknown name")
.onAppear {
calories = food.calories
name = food.name!
}
Spacer()
Text(calcTimeSince(date:food.date!))
.foregroundColor(.gray)
.font(.caption)
.italic()
}///-HStack
ZStack {
Rectangle()
.foregroundColor(ColouredBars())
.frame(width: food.calories/3, height: 15, alignment: .trailing)
.cornerRadius(5)
Text("\(Int(food.calories))")
.foregroundColor(.white)
.font(.caption)
}///-ZStack
}///-VStack
}///ForEach Ends
}///-List
}///-View
func ColouredBars() -> Color {
let calories: Double = 299
if calories > 600 {
color = .red
} else if calories > 300 {
color = .yellow
} else {
color = .green
}
return color
}
}///-Struct
struct ColourChart_Previews: PreviewProvider {
static var previews: some View {
ColourChart()
}
}
You would want to add a calories parameter and change the return type to color. The code would look something like this:
func calorieColor(calorie: Double) -> Color {
if calorie >= 600 {
return .red
} else if calorie >= 300 {
return .yellow
} else {
return .green
}
return .clear
}
the .clear is there just to allow the function to return some type of color if the if statement isn't applicable but that shouldn't be the case.
You could also do func calorieColor(_ calorie: Double) -> Color { The _ allows you to make the code a little more concise by allowing you to just type calorieColor(150) vs calorieColor(Calorie: 150).

How do I make conjoined buttons in SwiftUI? (MacOS)

There are buttons present in apps, such as TextEdit where the sides of adjacent buttons are joined together. Does anyone know how I could replicate this visual? I'm working in SwiftUI on MacOS, and answers for MacOS 10 & 11 would be appreciated.
I don’t think that’s possible in SwiftUI, unless you want to build it from scratch. What you’re seeing in TextEdit is an NSSegmentedControl that allows multiple selection: https://developer.apple.com/design/human-interface-guidelines/macos/selectors/segmented-controls/
In SwiftUI, segmented controls are made using Picker, which doesn’t allow multiple selection. Your best bet is to wrap NSSegmentedControl in an NSHostingView.
Replicating these buttons using SwiftUI is not all that difficult.
Here is a very basic approach, adjust the colors, corners etc... to your liking:
import SwiftUI
#main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
TextFormats()
}
}
struct GrayButtonStyle: ButtonStyle {
let w: CGFloat
let h: CGFloat
init(w: CGFloat, h: CGFloat) {
self.w = w
self.h = h
}
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(Color.white)
.frame(width: w, height: h)
.padding(5)
.background(Color(UIColor.systemGray4))
.overlay(Rectangle().strokeBorder(Color.gray, lineWidth: 1))
}
}
struct TextFormats: View {
let sx = CGFloat(20)
let color = Color.black
#State var bold = false
#State var italic = false
#State var underline = false
var body: some View {
HStack (spacing: 0) {
Group {
Button(action: { bold.toggle() }) {
Image(systemName: "bold").resizable().frame(width: sx, height: sx)
.foregroundColor(bold ? .blue : color)
}
Button(action: { italic.toggle() }) {
Image(systemName: "italic").resizable().frame(width: sx, height: sx)
.foregroundColor(italic ? .blue : color)
}
Button(action: { underline.toggle() }) {
Image(systemName: "underline").resizable().frame(width: sx, height: sx)
.foregroundColor(underline ? .blue : color)
}
}.buttonStyle(GrayButtonStyle(w: sx+5, h: sx+5))
}.padding(1)
.overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(.white, lineWidth: 2))
.clipped(antialiased: true)
}
}

Show line / separator view in SwiftUI

I want to show a separator line in my SwiftUI app. To achieve that, I tried to create an empty view with a fixed frame and a background color / border:
EmptyView()
.frame(width: 200, height: 2)
.background(Color.black) // or:
.border(Color.black, width: 2)
Unfortunately, I cannot see any dark view showing up.
Is there a way to show a separator / line view?
Use Divider:
A visual element that can be used to separate other content.
Example:
struct ContentView : View {
var body: some View {
VStack {
Text("Hello World")
Divider()
Text("Hello Another World")
}
}
}
Output:
If anyone is interested a divider, text, divider, looking like this:
LabelledDivider code
struct LabelledDivider: View {
let label: String
let horizontalPadding: CGFloat
let color: Color
init(label: String, horizontalPadding: CGFloat = 20, color: Color = .gray) {
self.label = label
self.horizontalPadding = horizontalPadding
self.color = color
}
var body: some View {
HStack {
line
Text(label).foregroundColor(color)
line
}
}
var line: some View {
VStack { Divider().background(color) }.padding(horizontalPadding)
}
}
It's kind of ugly but I had to put the Dividers into a VStack to make them horizontal, otherwise, they will be vertical, due to HStack. Please let me know if you managed to simplify this :)
Also maybe using and stored properties for LabelledDivider might not be the most SwiftUI-y solution, so I'm open to improvements.
Example usage
This is the code that results in the screenshot seen above:
struct GetStartedView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: SignInView()) {
Text("Sign In").buttonStyleEmerald()
}
LabelledDivider(label: "or")
NavigationLink(destination: SignUpView()) {
Text("Sign up").buttonStyleSaphire()
}
}.padding(20)
}
}
}
ButtonStyle
For sake of completness, I also include buttonStyle view modifiers:
struct ButtonStyle: ViewModifier {
private let color: Color
private let enabled: () -> Bool
init(color: Color, enabled: #escaping () -> Bool = { true }) {
self.color = color
self.enabled = enabled
}
dynamic func body(content: Content) -> some View {
content
.padding()
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.foregroundColor(Color.white)
.background(enabled() ? color : Color.black)
.cornerRadius(5)
}
}
extension View {
dynamic func buttonStyleEmerald(enabled: #escaping () -> Bool = { true }) -> some View {
ModifiedContent(content: self, modifier: ButtonStyle(color: Color.emerald, enabled: enabled))
}
dynamic func buttonStyleSaphire(enabled: #escaping () -> Bool = { true }) -> some View {
ModifiedContent(content: self, modifier: ButtonStyle(color: Color.saphire, enabled: enabled))
}
}
Edit: Please note that Color.saphire and Color.emerald are custom declared colors:
extension Color {
static var emerald: Color { .rgb(036, 180, 126) }
static var forest: Color { .rgb(062, 207, 142) }
}
extension Color {
static func rgb(_ red: UInt8, _ green: UInt8, _ blue: UInt8) -> Color {
func value(_ raw: UInt8) -> Double {
return Double(raw)/Double(255)
}
return Color(
red: value(red),
green: value(green),
blue: value(blue)
)
}
}
You can just draw a line by using Color. If you want to change the line width or padding, you can use frame or padding like other SwiftUI Components.
//Horizontal Line in VStack
VStack{
Color.gray.frame(height: 1 / UIScreen.main.scale)
}
//Vertical Line in HStack
HStack{
Color.gray.frame(width: 1 / UIScreen.main.scale)
}
If you are looking for a way to customize the divider, there isn't any. You must provide your custom implementation:
struct CustomDivider: View {
let height: CGFloat = 1
let color: Color = .white
let opacity: Double = 0.2
var body: some View {
Group {
Rectangle()
}
.frame(height: height)
.foregroundColor(color)
.opacity(opacity)
}
}
HStack {
VStack {
Divider()
}
Text("or")
.font(.caption)
.foregroundColor(Color(UIColor.systemGray))
VStack {
Divider()
}
}