How to have a custom alignment guide permeate a ScrollView in SwiftUI - swift

I want to be able to align things in a ZStack. Some of these things are in a ScrollView in the ZStack, and some are not. I can get the things that are in the ScrollView to align with each other, and things outside the ScrollView to align with each other, but I cannot get them to all align. I can do if I just remove the ScrollView, so for instance:
extension VerticalAlignment {
enum MidAccountAndName: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[.top]
}
}
static let midAccountAndName = VerticalAlignment(MidAccountAndName.self)
}
struct ContentView: View {
var body: some View {
ZStack(alignment: Alignment(horizontal: .center, vertical: .midAccountAndName)) {
Rectangle()
.alignmentGuide(.midAccountAndName) { d in
d[VerticalAlignment.center]
}
.frame(width: 1000, height: 2)
HStack(alignment: .midAccountAndName) {
VStack {
Text("Left-hand text")
.alignmentGuide(.midAccountAndName) { d in
d[VerticalAlignment.center]
}
Text("More text")
}
VStack {
Text("Right-hand text")
Text("Title")
.alignmentGuide(.midAccountAndName) { d in
d[VerticalAlignment.center]
}
.font(.largeTitle)
}
}
}
}
}
Results in this, which is what I want:
But this code:
extension VerticalAlignment {
enum MidAccountAndName: AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
d[.top]
}
}
static let midAccountAndName = VerticalAlignment(MidAccountAndName.self)
}
struct ContentView: View {
var body: some View {
ZStack(alignment: Alignment(horizontal: .center, vertical: .midAccountAndName)) {
Rectangle()
.alignmentGuide(.midAccountAndName) { d in
d[VerticalAlignment.center]
}
.frame(width: 1000, height: 2)
ScrollView {
HStack(alignment: .midAccountAndName) {
VStack {
Text("Left-hand text")
.alignmentGuide(.midAccountAndName) { d in
d[VerticalAlignment.center]
}
Text("More text")
}
VStack {
Text("Right-hand text")
Text("Title")
.alignmentGuide(.midAccountAndName) { d in
d[VerticalAlignment.center]
}
.font(.largeTitle)
}
}
}
}
}
}
Results in this, which is undesirable:
Can anyone help me get the former behaviour working in concert with the ScrollView?

How about this?
struct ContentView: View {
let largeFont = Font.largeTitle
let smallFont = Font.body
var body: some View {
HStack {
HStack {
VStack {
Text("|")
.font(largeFont)
.frame(width: 0)
Text("Left-hand text")
Text("More Text")
}
.font(smallFont)
}
HStack {
VStack {
Text("Right-hand text")
HStack {
Text("Title")
.font(largeFont)
}
}
.font(smallFont)
}
}
}
}
The trick is to use a placeholder at width: 0 on the other side of the HStack in your VStacks. I made the font variables so that you could change the relative sizes without accidentally messing up the alignment. There is usually a simple way in SwiftUI to achieve your layout, and let the OS do the work for you.

Related

Fit GeometryReader to drawer contents

How can I fit the GeometryReader to the middle ExpandingDrawer contents?
(Copy & Paste-able):
import SwiftUI
struct ExpandingDrawerButton: View {
#Binding var isExpanded: Bool
var body: some View {
Button(action: { withAnimation { isExpanded.toggle() } }) {
Text(isExpanded ? "Close" : "Open")
}
}
}
struct ExpandingDrawer<Content: View>: View {
#Binding var isExpanded: Bool
var content: () -> Content
var body: some View {
content()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: nil, maxHeight: contentHeight)
.allowsHitTesting(isExpanded)
.clipped()
.transition(.slide)
}
private var contentHeight: CGFloat? {
isExpanded ? nil : CGFloat(0)
}
}
struct DrawerTestView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
struct ContentView: View {
#State var isExpanded = false
var body: some View {
GeometryReader { geo in
VStack(spacing: 0) {
top
.frame(height: geo.size.height * 1/4)
middle
bottom
.frame(height: geo.size.width)
}
}
}
var top: some View {
ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
Rectangle()
.foregroundColor(.blue.opacity(0.2))
ExpandingDrawerButton(isExpanded: $isExpanded)
.padding()
}
}
var middle: some View {
ExpandingDrawer(isExpanded: $isExpanded) {
middleContent
}
}
var middleContent: some View {
GeometryReader { geo in
VStack {
ForEach(0..<10) { _ in
Button(action: {}) { Text("Random shit") }
}
Text("Don't know how tall...")
Text("Height can change...")
Text("But does need to fit snug (no extra space)")
}
}
}
var bottom: some View {
ZStack {
Rectangle()
.foregroundColor(.red)
.aspectRatio(1, contentMode: .fit)
VStack {
Text("Needs to be a square...")
Text("Okay if pushed below edge of screen...")
}
}
}
}
}
I've tried various combinations of .fixedSize() and .aspectRatio() but I'm struggling...
To avoid GeometryReader changing our views, we can put it in an .overlay().
Example:
struct ContentView: View {
class Storage {
var geo: GeometryProxy! {
didSet {
print(geo.size)
}
}
}
let storage = Storage()
/* ... */
}
var middleContent: some View {
VStack {
ForEach(0..<10) { _ in
Button(action: {}) { Text("Random stuff") }
}
Text("Don't know how tall...")
Text("Height can change...")
Text("But does need to fit snug (no extra space)")
}
.overlay(
GeometryReader { geo in
Rectangle()
.fill(Color.clear)
let _ = storage.geo = geo
}
)
}
You can now use storage.geo to access the GeometryProxy of this view.

How to use .firstTextBaseline alignment with a view that contains GeometryReader

I have two views in a HStack - the left one is a simple Text view.
For the right view, i'm experimenting with using GeometryReader. I cannot get the baselines of the text aligned when I use geometry reader, but I can when I don't use it.
Here is some code:
struct CompositeView : View {
var body : some View {
VStack {
Button(action: {
}) {
Text("Another text")
.padding(5)
.overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.blue, lineWidth: 2.0))
}
}
}
}
struct GeometryReaderTest : View {
var tags: [String]
init(tags : [String]) {
self.tags = tags
}
#State private var viewHeight = CGFloat.zero
var body: some View {
VStack {
GeometryReader { geometry in
ZStack {
ForEach(self.tags, id: \.self) { tag in
Button(action: {}) {
Text(tag)
.padding(5)
.overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.blue, lineWidth: 2.0))
}
}
}
.background(getHeight(self.$viewHeight))
}
}
.frame(height: viewHeight)
}
/// Get the height of the Geometry view
///
private func getHeight(_ height: Binding<CGFloat>) -> some View {
return GeometryReader { geometry -> Color in
let rect = geometry.frame(in: .local)
DispatchQueue.main.async {
height.wrappedValue = rect.size.height
}
return .clear
}
}
}
struct MyTestView : View {
var body : some View {
VStack {
HStack (alignment: .firstTextBaseline) {
ZStack {
Text("Hello")
}
GeometryReaderTest(tags: ["One"])
}
HStack (alignment: .firstTextBaseline) {
ZStack {
Text("Hello")
}
CompositeView()
}
}
}
}
Here is the outcome:
As you can see, the baseline alignment doesn't work when the right hand view is a GeometryReader, but it does work when the right hand view is a simple button.
Does anyone know how I can get the baselines to line up?
I'm using GeometryReader because my right-view will eventually be more complex - I'm reducing the issue I'm facing to as small a repro as possible.
Thank you!

Tabbar middle button utility function in SwiftUI

I'm trying to reproduce a "Instagram" like tabBar which has a "Utility" button in the middle which doesn't necessarily belong to the tabBar eco system.
I have attached this gif to show the behaviour I am after. To describe the issue. The tab bar in the middle (Black plus) is click a ActionSheet is presented INSTEAD of switching the view.
How I would do this in UIKit is simply use the
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
print("Selected item")
}
Function from the UITabBarDelegate. But obviously we can't do this in SwiftUI so was looking to see if there was any ideas people have tried. My last thought would be to simply wrap it in a UIView and use it with SwiftUI but would like to avoid this and keep it native.
I have seen a write up in a custom TabBar but would like to use the TabBar provided by Apple to avoid any future discrepancies.
Thanks!
Edit: Make the question clearer.
Thanks to Aleskey for the great answer (Marked as correct). I evolved it a little bit in addition to a medium article that was written around a Modal. I found it to be a little different
Here's the jist.
A MainTabBarData which is an Observable Object
final class MainTabBarData: ObservableObject {
/// This is the index of the item that fires a custom action
let customActiontemindex: Int
let objectWillChange = PassthroughSubject<MainTabBarData, Never>()
var previousItem: Int
var itemSelected: Int {
didSet {
if itemSelected == customActiontemindex {
previousItem = oldValue
itemSelected = oldValue
isCustomItemSelected = true
}
objectWillChange.send(self)
}
}
func reset() {
itemSelected = previousItem
objectWillChange.send(self)
}
/// This is true when the user has selected the Item with the custom action
var isCustomItemSelected: Bool = false
init(initialIndex: Int = 1, customItemIndex: Int) {
self.customActiontemindex = customItemIndex
self.itemSelected = initialIndex
self.previousItem = initialIndex
}
}
And this is the TabbedView
struct TabbedView: View {
#ObservedObject private var tabData = MainTabBarData(initialIndex: 1, customItemIndex: 2)
var body: some View {
TabView(selection: $tabData.itemSelected) {
Text("First Screen")
.tabItem {
VStack {
Image(systemName: "globe")
.font(.system(size: 22))
Text("Profile")
}
}.tag(1)
Text("Second Screen")
.tabItem {
VStack {
Image(systemName: "plus.circle")
.font(.system(size: 22))
Text("Profile")
}
}.tag(2)
Text("Third Screen")
.tabItem {
VStack {
Image(systemName: "number")
.font(.system(size: 22))
Text("Profile")
}
}.tag(3)
}.actionSheet(isPresented: $tabData.isCustomItemSelected) {
ActionSheet(title: Text("SwiftUI ActionSheet"), message: Text("Action Sheet Example"),
buttons: [
.default(Text("Option 1"), action: option1),
.default(Text("Option 2"), action: option2),
.cancel(cancel)
]
)
}
}
func option1() {
tabData.reset()
// ...
}
func option2() {
tabData.reset()
// ...
}
func cancel() {
tabData.reset()
}
}
struct TabbedView_Previews: PreviewProvider {
static var previews: some View {
TabbedView()
}
}
Similar concept, just uses the power of SwiftUI and Combine.
You could introduce new #State property for storing old tag of presented tab. And perform the next method for each of your tabs .onAppear { self.oldSelectedItem = self.selectedItem } except the middle tab. The middle tab will be responsible for showing the action sheet and its method will look the following:
.onAppear {
self.shouldShowActionSheet.toggle()
self.selectedItem = self.oldSelectedItem
}
Working example:
import SwiftUI
struct ContentView: View {
#State private var selectedItem = 1
#State private var shouldShowActionSheet = false
#State private var oldSelectedItem = 1
var body: some View {
TabView (selection: $selectedItem) {
Text("Home")
.tabItem { Image(systemName: "house") }
.tag(1)
.onAppear { self.oldSelectedItem = self.selectedItem }
Text("Search")
.tabItem { Image(systemName: "magnifyingglass") }
.tag(2)
.onAppear { self.oldSelectedItem = self.selectedItem }
Text("Add")
.tabItem { Image(systemName: "plus.circle") }
.tag(3)
.onAppear {
self.shouldShowActionSheet.toggle()
self.selectedItem = self.oldSelectedItem
}
Text("Heart")
.tabItem { Image(systemName: "heart") }
.tag(4)
.onAppear { self.oldSelectedItem = self.selectedItem }
Text("Profile")
.tabItem { Image(systemName: "person.crop.circle") }
.tag(5)
.onAppear { self.oldSelectedItem = self.selectedItem }
}
.actionSheet(isPresented: $shouldShowActionSheet) { ActionSheet(title: Text("Title"), message: Text("Message"), buttons: [.default(Text("Option 1"), action: option1), .default(Text("Option 2"), action: option2) , .cancel()]) }
}
func option1() {
// do logic 1
}
func option2() {
// do logic 2
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Previous answers did not help me so I'm pasting my complete solution.
import SwiftUI
import UIKit
enum Tab {
case map
case recorded
}
#main
struct MyApp: App {
#State private var selectedTab: Tab = .map
#Environment(\.scenePhase) private var phase
var body: some Scene {
WindowGroup {
VStack {
switch selectedTab {
case .map:
NavigationView {
FirstView()
}
case .recorded:
NavigationView {
SecondView()
}
}
CustomTabView(selectedTab: $selectedTab)
.frame(height: 50)
}
}
}
}
struct FirstView: View {
var body: some View {
Color(.systemGray6)
.ignoresSafeArea()
.navigationTitle("First view")
}
}
struct SecondView: View {
var body: some View {
Color(.systemGray6)
.ignoresSafeArea()
.navigationTitle("second view")
}
}
struct CustomTabView: View {
#Binding var selectedTab: Tab
var body: some View {
HStack {
Spacer()
Button {
selectedTab = .map
} label: {
VStack {
Image(systemName: "map")
.resizable()
.scaledToFit()
.frame(width: 25, height: 25)
Text("Map")
.font(.caption2)
}
.foregroundColor(selectedTab == .map ? .blue : .primary)
}
.frame(width: 60, height: 50)
Spacer()
Button {
} label: {
ZStack {
Circle()
.foregroundColor(.secondary)
.frame(width: 80, height: 80)
.shadow(radius: 2)
Image(systemName: "plus.circle.fill")
.resizable()
.foregroundColor(.primary)
.frame(width: 72, height: 72)
}
.offset(y: -2)
}
Spacer()
Button {
selectedTab = .recorded
} label: {
VStack {
Image(systemName: "chart.bar")
.resizable()
.scaledToFit()
.frame(width: 25, height: 25)
Text("Recorded")
.font(.caption2)
}
.foregroundColor(selectedTab == .recorded ? .blue : .primary)
}
.frame(width: 60, height: 50)
Spacer()
}
}
}

Presenting - Show a view on top in SwiftUI (I don't want to navigate)

Hey There I want to show a custom View in the middle of View I've tried to add ZStack and centered but doesn't work.. here's my code
var body: some View {
VStack(alignment: .leading, spacing: 8) {
headerView.padding().background(Color.white)
ZStack(alignment: .center) {
if(incomeFill_show) {
BudgetAlert(amount: .constant("400"))
}
List() {
VStack {
Section(header: self.getHeaderView()) {
ForEach(categoriesData) { category in
HStack(alignment: .bottom) {
CategoryProgressView(category: category, value: .constant(.random(in: 0.1 ... 1)))
self.valuesText(category: category)
}
}
.colorMultiply(Colors.SharedColors.backgroundColor)
}
}
}
.colorMultiply(Colors.SharedColors.backgroundColor)
.onAppear {UITableView.appearance().separatorStyle = .none}
.onDisappear { UITableView.appearance().separatorStyle = .singleLine }
}
}.background(Colors.SharedColors.backgroundColor)
}
all I want is to show BudgetAlert() with blurred background like this:
I solved it by placing
if(incomeFill_show) {
BudgetAlert(amount: .constant("400"))
}
at the bottom of the List: like this
var body: some View {
VStack(alignment: .leading, spacing: 8) {
headerView.padding().background(Color.white)
ZStack(alignment: .center) {
List() {
VStack {
Section(header: self.getHeaderView()) {
ForEach(categoriesData) { category in
HStack(alignment: .bottom) {
CategoryProgressView(category: category, value: .constant(.random(in: 0.1 ... 1)))
self.valuesText(category: category)
}
}
.colorMultiply(Colors.SharedColors.backgroundColor)
}
}
}
.colorMultiply(Colors.SharedColors.backgroundColor)
.onAppear {UITableView.appearance().separatorStyle = .none}
.onDisappear { UITableView.appearance().separatorStyle = .singleLine }
if(incomeFill_show) {
BudgetAlert(amount: .constant("400"))
}
}
}.background(Colors.SharedColors.backgroundColor)
}
}
for blurred background you can see this code here:
var body: some View {
VStack {
Spacer()
ZStack(alignment: .center) {
RoundedRectangle(cornerRadius: 10).foregroundColor(Color.white)
VStack {
Text("Add your Income").font(Fonts.mediumFont)
HStack(alignment: .center, spacing: 0) {
CustomTextField(placeHolderLabel: "Amount", val: $amount, keyboardType: UIKeyboardType.decimalPad).padding()
HStack {
Button("\(currency.rawValue)"){
self.show_currencyActionsheet = true
}
.font(Fonts.callout)
.foregroundColor(Colors.textFieldFloatingLabel)
.actionSheet(isPresented: self.$show_currencyActionsheet) {self.actionSheetCurrency}
Image(systemName: "chevron.down")
.imageScale(.small)
}.padding()
}.padding([.leading,.trailing])
Button(action: {
self.callBack()
}) {
Text(" Add Income ").font(Fonts.callout).foregroundColor(Color.white)
}
.padding()
.background(Colors.darkGreen)
.clipShape(Capsule())
}
}.frame(minHeight: 150, idealHeight: 182, maxHeight: 200)
.padding()
Spacer()
}.background(VisualEffectView(effect: UIBlurEffect(style: .dark))
.edgesIgnoringSafeArea(.all))
}
struct VisualEffectView: UIViewRepresentable {
var effect: UIVisualEffect?
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIVisualEffectView { UIVisualEffectView() }
func updateUIView(_ uiView: UIVisualEffectView, context: UIViewRepresentableContext<Self>) { uiView.effect = effect }
}
but I prefer to go with faded background

Views compressed by other views in SwiftUI VStack and List

In my SwiftUI application, I'm trying to implement a UI similar to this:
I've added the two rows for category 1 and category 2. The result looks like this:
NavigationView {
VStack(alignment: .leading) {
CategoryRow(...)
CategoryRow(...)
Spacer()
}
.navigationBarTitle(Text("Featured"))
}
Now, when added the view for the third category – an VStack with images – the following happens:
This happened, after I replaced Spacer(), with said VStack:
VStack(alignment: .leading) {
Text("Rivers")
.font(.headline)
ForEach(self.categories["Rivers"]!.identified(by: \.self)) { landmark in
landmark.image(forSize: 200)
}
}
My CategoryRow is implemented as follows:
VStack(alignment: .leading) {
Text(title)
.font(.headline)
ScrollView {
HStack {
ForEach(landmarks) { landmark in
CategoryItem(landmark: landmark, isRounded: self.isRounded)
}
}
}
}
Question
It seems that the views are compressed. I was not able to find any compression resistance or content hugging priority modifiers to fix this.
I also tried to use .fixedSize() and .frame(width:height:) on CategoryRow.
How can I prevent the compression of these views?
Update
I've tried embedding the whole outer stack view in a scroll view:
NavigationView {
ScrollView { // also tried List
VStack(alignment: .leading) {
CategoryRow(...)
CategoryRow(...)
ForEach(...) { landmark in
landmark.image(forSize: 200)
}
}
.navigationBarTitle(Text("Featured"))
}
}
...and the result is worse:
You might prevent the views in VStack from being compressed by using
.fixedSize(horizontal: false, vertical: true)
For example:
I have the following VStack:
VStack(alignment: .leading){
ForEach(group.items) {
FeedCell(item: $0)
}
}
Which render compressed Text()
When I add .fixedSize(horizontal: false, vertical: true)
it doesn't compress anymore
VStack(alignment: .leading){
ForEach(group.items) {
FeedCell(item: $0)
.fixedSize(horizontal: false, vertical: true)
}
}
You could try to add a layoutPriority()operator to your first VStack. This is what the documentation says about the method:
In a group of sibling views, raising a view’s layout priority encourages that view to shrink later when the group is shrunk and stretch sooner when the group is stretched.
So it's a bit like the content compression resistance priority in Autolayout. But the default value here is 0, so you just have to set it to 1 to get the desired effect, like this:
VStack(alignment: .leading) {
CategoryRow(...)
CategoryRow(...)
Spacer()
}.layoutPriority(1)
VStack(alignment: .leading) {
...
}
Hope it works!
It looks like is not enough space for all your views in VStack, and it compresses some of them. You can embed it into the ScrollView
NavigationView {
ScrollView {
VStack(alignment: .leading) {
CategoryRow(...)
CategoryRow(...)
/// you images and so on
}
}
}
struct ContentView1: View {
var body: some View {
NavigationView {
ScrollView {
VStack {
CategoryListView {
CategoryView()
}
CategoryListView {
SquareCategoryView()
}
CategoryListView {
RectangleCategoryView()
}
}
.padding()
}
.navigationTitle("Featured")
}
}
}
struct CategoryListView<Content>: View where Content: View {
private let viewSize: CGFloat = 150
var content: () -> Content
init(#ViewBuilder content: #escaping () -> Content) {
self.content = content
}
var body: some View {
VStack {
HStack {
Text("Category name")
Spacer()
}
ScrollView(.horizontal, showsIndicators: false){
HStack {
ForEach(0..<10) { _ in
content()
}
}
}
}
}
}
struct ContentView1_Previews: PreviewProvider {
static var previews: some View {
ContentView1()
}
}
struct CategoryView: View {
private let viewSize: CGFloat = 150
var body: some View {
Circle()
.fill()
.foregroundColor(.blue)
.frame(width: viewSize, height: viewSize)
}
}
struct RectangleCategoryView: View {
private let viewSize: CGFloat = 350
var body: some View {
Rectangle()
.fill()
.foregroundColor(.blue)
.frame(width: viewSize, height: viewSize * 9 / 16)
}
}
struct SquareCategoryView: View {
private let viewSize: CGFloat = 150
var body: some View {
Rectangle()
.fill()
.foregroundColor(.blue)
.frame(width: viewSize, height: viewSize)
}
}
I think your topmost view (in the NavigationView) needs to be a List, so that it is scrollable:
NavigationView {
List {
...
Or use a ScrollView.
A stack automatically fits within a screen. If you want your content to exceed this, you would have used a ScrollView or a TableView etc i UIKit
EDIT:
Actually, a little Googling brought this result, which seems to be exactly what you are making:
https://developer.apple.com/tutorials/swiftui/composing-complex-interfaces