How to add padding on form segments in SwiftUI - swift

In iOS 13, some native Apple apps use a list style I am struggling to recreate. It's basically a List within a Form containing Sections and some entries.
The only difference is that each Section has padding to the left and right side and a corner radius around the edges.
Here is an example from the Home app of what I would like to achieve (also used in the Timer tab in the Clock app):
Applying the .padding()-Modifier to the Form doesn't work.
struct ContentView: View {
var body: some View {
Form {
Section {
Text("foo")
Text("bar")
}
Section {
Text("foo")
}
Section {
Text("bar")
}
}
}
}
I am wondering if it is at all possible in SwiftUI or if this is just some UIKit-adjustment on a UITableViewCell.

This is new UITableView.Style called .insetGrouped. This is the documentation
You can set it with code:
let tableView = UITableView(frame: frame, style: .insetGrouped)
Or with Interface builder:
SwiftUI doesn't have this style (yet), but in the future, it should be a ListStyle that you can use with .listStyle modifier on a list. Currently available styles are:
.listStyle(DefaultListStyle()) // wich is PlainListStyle
.listStyle(PlainListStyle())
.listStyle(GroupedListStyle())
// .listStyle(InsetGroupedListStyle()) // unresolved (yet)

It is possible with this modification to Form or List:
Form {
Text("Hey")
}
.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)

Related

SwiftUI Add TextField to Menu

I have a menu and want to be able to input some data from the menu. This is what I've tried and it shows up in the menu, but doesn't allow any input. Is there a way to hack some input in SwiftUI Menus?
Menu("Award Users") {
TextField(awardedAmount, text: $awardedAmount)
Button("Send") {
}
}
SwiftUI will simplify the layout of the menu items, and if not possible, it may discard some of your items.
Not all views are suitable to work as a menu item and they will be silently ignored. These are some of the views that work: Menu, Text, Button, Link, Label, Divider or Image.
SwiftUI Menu gives us a dedicated view for showing popup button with the help of menus. Menu option is used to create variety of buttons to control what you want to appear in the menu. If you add a textfield, Menu View will consider it as button title and disable its action as shown in image below.
struct ContentView: View {
#State private var awardedAmount = "125"
var body: some View {
VStack{
Menu("Options") {
TextField(awardedAmount, text: $awardedAmount)
Button("Order Now", action: placeOrder)
Button("Adjust Order", action: adjustOrder)
Button("Cancel", action: cancelOrder)
}
}
}
func placeOrder() { }
func adjustOrder() { }
func cancelOrder() { }
}
So in short Menu is a dedicated view for buttons for selecting an option, not taking user inputs.

SwiftUI - Position an overlay relative to its anchor

I have a ZStack containing 2 views:
referenceContent - has some content and a Divider. This is the main content across the screen
popoverContent - is a conditional popup window that only takes up a tiny portion of the screen.
var body: some View {
ZStack {
referenceContent
if popoverCondition {
popoverContent
}
}
}
I want the popoverContent's top edge to line up with the bottom of referenceContent
Anyone know how to make this happen? Or is there just a much better way to view this popup window than I'm doing now? Thanks!
You can do this using the overlay(alignment:content:) modifier (previously overlay(_:alignment:)) in combination with custom alignment guides.
The basic idea is that you align the bottom of your reference view with the top of your popover view.
The annoying thing is that the overlay modifier only lets you specify one alignment guide (for the two views). So if you write stack1.overlay(alignment: .bottom) { stack2 } it will align the bottom of your reference with the bottom of your overlay. A quick way to overcome this is to overwrite the bottom alignment guide of your overlay and return the top instead.
referenceView
.overlay(alignment: .bottom) {
popoverContent
// overwrites bottom alignment of the popover with its top alignment guide.
.alignmentGuide(.bottom) {$0[.top]}
}
Overlay vs ZStack
You might ask: "why don't you use a ZStack instead of an overlay?". Well the difference between the two is that the ZStack will take the size of your popover into consideration when laying out your entire view (reference + popover). That is the opposite of what a popover should do. For a popover, the layout system should only take the size of your reference view into consideration and draw the popover on top of it (without affecting the layout of your reference). That is exactly what the overlay(...) modifier does.
Old API (prior to iOS 15, macOS 12)
In older versions of SwiftUI the arguments of the overlay modifier were in reverse order. So the code example for these older systems is:
referenceView
.overlay(
popoverContent.alignmentGuide(.bottom) {$0[.top]},
alignment: .bottom
)
Custom alignment guides
When you don't want to overwrite an existing alignment guide (because you need it somewhere else for example) you can also use a custom alignment guide. Here is a more generic example using a custom alignment guide named Alignment.TwoSided
extension View {
#available(iOS 15.0, *)
func overlay<Target: View>(align originAlignment: Alignment, to targetAlignment: Alignment, of target: Target) -> some View {
let hGuide = HorizontalAlignment(Alignment.TwoSided.self)
let vGuide = VerticalAlignment(Alignment.TwoSided.self)
return alignmentGuide(hGuide) {$0[originAlignment.horizontal]}
.alignmentGuide(vGuide) {$0[originAlignment.vertical]}
.overlay(alignment: Alignment(horizontal: hGuide, vertical: vGuide)) {
target
.alignmentGuide(hGuide) {$0[targetAlignment.horizontal]}
.alignmentGuide(vGuide) {$0[targetAlignment.vertical]}
}
}
}
extension Alignment {
enum TwoSided: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat { 0 }
}
}
You would use that like this:
referenceView
.overlay(align: .bottom, to: .top, of: popoverContent)

Toggle Sidebar in Code using SwiftUI NavigationView on iPad

I'm trying to utilize the built-in sidebar from SwiftUI 2.0 by using NavigationView like this:
NavigationView {
MainView()
ListView()
DetailView()
}.navigationBarHidden(true)
But since I want to use my own Custom Back Button, I've hidden the NavigationBar and tried to toggle the sidebar with code which doesn't work.
self.presentationMode.wrappedValue.dismiss()
I've already seen a lot of solutions for macOS:
NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
But I can't seem to find equivalent for iPad, thanks in advance.
I used this code to change the default sidebar settings:
extension UISplitViewController {
open override func viewDidLoad() {
super.viewDidLoad()
self.preferredDisplayMode = .secondaryOnly
self.preferredSplitBehavior = .overlay
}
}
self exposes several sidebar methods and properties that can be used. I hope it will be useful!
So this is not a good long term solution but if you are like me and 100% needed the native approach to work here's how it can be hacked. Using https://github.com/siteline/SwiftUI-Introspect you can find the right view controller in the hierarchy and set the display mode.
Text("Some View").introspectViewController { vc in
guard let splitVC = vc.parent?.parent as? UISplitViewController else {
return
}
splitVC.preferredDisplayMode = .oneBesideSecondary
}
This is BRITTLE but it works.

Set segment equal width for SwiftUI Picker with SegmentedPickerStyle

Using the SegmentedPickerStyle style Picker could make the control looks like UISegmentedControl. But I wonder how to adjust the segment width in the picker. For examle, the picker in the image has a different width for text.
Is there a way to make the segments the same width in the SwiftUI?
Picker(selection: $store.utility.saliencyType, label: EmptyView()) {
ForEach(Store.Utility.SaliencyType.allCases, id: \.self) { saliencyType in
Text(saliencyType.text)
.tag(saliencyType)
}
}.pickerStyle(SegmentedPickerStyle())
...For examle, the picker in the image has a different width for text.
In case you arrive here seeking for iOS SwiftUI SegmentedPickerStyle solution... I've found the iOS SwiftUI .pickerStyle(SegmentedPickerStyle()) will conform to global UISegmentedControl.appearance() settings, so I've used the following to successfully apportion the width of each segment:
UISegmentedControl.appearance().apportionsSegmentWidthsByContent = true
This is particularly useful if, for example, you want to support Dynamic Type fonts in your app, which can otherwise cause segments with longer names to blow out and get truncated. [aside: I also use this trick to change the SwiftUI segmented picker's font size! see https://stackoverflow.com/a/71834578/3936065]
This is default macOS NSSegmetedControl behavirour
#property NSSegmentDistribution segmentDistribution API_AVAILABLE(macos(10.13));
// Defaults to NSSegmentDistributionFill on 10.13, older systems will continue to behave similarly to NSSegmentDistributionFit
Update: here is workaround, based on finding NSSegmentedControl in run-time view hierarchy.
Disclaimer: Actually it is safe, ie. no crash in run-time, but can stop working in future returning to default behaviour.
So, the idea is to inject NSView via representable into view hierarchy above (!!) Picker, as
Picker(selection: $store.utility.saliencyType, label: EmptyView()) {
ForEach(Store.Utility.SaliencyType.allCases, id: \.self) { saliencyType in
Text(saliencyType.text)
.tag(saliencyType)
}
}
.overlay(NSPickerConfigurator { // << here !!
$0.segmentDistribution = .fillEqually // change style !!
})
.pickerStyle(SegmentedPickerStyle())
and configurator itself
struct NSPickerConfigurator: NSViewRepresentable {
var configure: (NSSegmentedControl) -> Void
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async {
if let holder = view.superview?.superview {
let subviews = holder.subviews
if let nsSegmented = subviews.first?.subviews.first as? NSSegmentedControl {
self.configure(nsSegmented)
}
}
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
}
}
Ah the reach down to AppKit method.
Very clever indeed.
However this is not working for me, Monteray 12.3
Went to debug further using Xcode's Visual Debugger and I can see the NSPickerConfigurator class in the view hierarchy but no NSSegmetedControl.
It appears as if apple is clearing up NSViews from the hierarchy.
Time to think pure swiftui.

How to get accentColor background for menu items in SwiftUI with reduced transparency?

Using AppKit you can add NSMenuItems to an NSMenu. I saw that there is something similar to NSMenu in SwiftUI, namely MenuButton. But I cannot find any documentation on how it works.
I tried the following:
MenuButton("+") {
Button("New contact") { print("Create new contact") }
Button("New group") { print("Create new group") }
}
And that gives me this
It looks almost OK but when I enable the "Reduce transparency" in system preferences
The buttons have a different background color than the menu (notice the slightly lighter color above and beneath the menu items).
When I hover the menu items, their background color doesn't change like a normal macOS menu. See the image below:
I also tried to change the background color manually using the .background() modifier but that doesn't affect the full width of the menu item.
MenuButton("+") {
Button("New contact") { print("Create new contact") }
.background(Color.accentColor)
Button("New group") { print("Create new group") }
}
I suppose this is because I am placing Buttons inside the MenuButton while it is probably expecting some other SwiftUI element. What elements should I place inside MenuButtons to create a normal looking macOS menu like the one below?
[Update] macOS Big Sur
I also tried this out in Big Sur. While the background renders correctly, in Big Sur, the text color is messed up now. 🤯
I think I found a partial solution to this by configuring a ButtonStyle and applying it to the MenuButton generic structure. Note however that the conditional change of .foregroundColor isn't inherited by the individual's Button()'s Text(). Also the color ain't right.
Perhaps someone wants to improve on this.
struct DetectHover: ButtonStyle {
#State private var hovering: Bool = false
public func makeBody(configuration: DetectHover.Configuration) -> some View {
configuration.label
.foregroundColor(self.hovering ? Color.white : Color.primary)
.background(self.hovering ? Color.blue : Color.clear)
.onHover { hover in
self.hovering = hover
}
}
}
MenuButton(label: Image(nsImage: NSImage(named: NSImage.actionTemplateName)!)) {
// Buttons
}.buttonStyle(DetectHover())
I’ve got something that nearly looks right. I have created a custom button which does change appearance when hovered.
I am very new to both Swift and SwiftUI, so the following may be clumsy. I would welcome any improvements.
struct HoverButton: View {
var text = "Hover Button"
var action = {}
#State private var hovering = false
var body: some View {
Button(text, action: action )
.padding(.horizontal, 6)
.padding(.vertical, 2)
.buttonStyle(PlainButtonStyle())
.frame(minWidth: 0, maxWidth: .infinity)
.background(self.hovering ? Color(.selectedMenuItemColor) : Color(.clear))
.onHover { hover in
self.hovering = hover
}
}
}
// Usage:
MenuButton("Test") {
HoverButton(text: "Apple", action: {
print("Apple")
})
HoverButton(text: "Banana", action: {
print("Banana")
})
}
.font(.system(size: 14, /* weight: .heavy, */ design: .default))
.menuButtonStyle(BorderlessButtonMenuButtonStyle())
The whole point in creating the custom button is to have access to Self so that I can change its appearance. However, there are some serious shortcomings:
The main problem is that the buttons don’t take the full width of the menu body. I have no idea how to fix that.
The menu buttons are centered. I tried using a HStack with a Spacer() but that didn’t help.
I have no idea how to omit the first parameter name as for a real Button