How to fit horizontal ScrollView to content's height? - ios

I have a horizontal scroll view with a LazyHStack. How do I size the scroll view to automatically fit the content inside?
By default, ScrollView takes up all the vertical space possible.
struct ContentView: View {
var numbers = 1...100
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(numbers, id: \.self) {
Text("\($0)")
.font(.largeTitle)
}
}
}
}
}

This code can be MUCH better
I have show it as BASE for your final solution
But it works
struct ContentView1111: View {
var numbers = 1...100
var body: some View {
VStack {
FittedScrollView(){
AnyView(
LazyHStack {
ForEach(numbers, id: \.self) {
Text("\($0)")
.font(.largeTitle)
}
}
)
}
// you can see it on screenshot - scrollView size
.background(Color.purple)
Spacer()
}
// you can see it on screenshot - other background
.background(Color.green)
}
}
struct HeightPreferenceKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue: CGFloat = 40
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
struct FittedScrollView: View {
var content: () -> AnyView
#State private var contentHeight: CGFloat = 40
var body: some View {
VStack {
ScrollView(.horizontal) {
content()
.overlay(
GeometryReader { geo in
Color.clear
.preference(key: HeightPreferenceKey.self, value: geo.size.height)
})
}
.frame(height: contentHeight)
}
.onPreferenceChange(HeightPreferenceKey.self) {
contentHeight = $0
}
}
}

Related

How can I add a more rows of buttons in my frame when my hstack is too long in Swift UI?

I would like to make the second row appear when my list is too long.
Do you have any idea how to do that?
Thank you in advance!
import SwiftUI
struct ContentView: View {
#StateObject var vm = SpeakingVM()
var speakingModel: SpeakingModel
var body: some View {
HStack(spacing:20){
ForEach(speakingModel.sentence.indices) { index in
Button(action: {
}, label: {
Text(speakingModel.sentence[index].definition)
.padding(.vertical,10)
.padding(.horizontal)
.background(Capsule().stroke(Color.blue))
.lineLimit(1)
})
}
}.frame(width: UIScreen.main.bounds.width - 30, height: UIScreen.main.bounds.height / 3)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(speakingModel: SpeakingModel(sentence: [SpeakingModel.Word(definition: "Météo"),SpeakingModel.Word(definition: "Cheval"),SpeakingModel.Word(definition: "Ascenceur")], sentenceInFrench: "Quel temps fait-il ?"))
}
}
What i would like :
Put your data in tags and customize the item view and change it appropriately.
import SwiftUI
struct HashTagView: View {
#State var tags: [String] = ["#Lorem", "#Ipsum", "#dolor", "#consectetur", "#adipiscing", "#elit", "#Nam", "#semper", "#sit", "#amet", "#ut", "#eleifend", "#Cras"]
#State private var totalHeight = CGFloat.zero
var body: some View {
VStack {
GeometryReader { geometry in
self.generateContent(in: geometry)
}
}
.frame(height: totalHeight)
}
private func generateContent(in g: GeometryProxy) -> some View {
var width = CGFloat.zero
var height = CGFloat.zero
return ZStack(alignment: .topLeading) {
ForEach(self.tags, id: \.self) { tag in
self.item(for: tag)
.padding([.horizontal, .vertical], 4)
.alignmentGuide(.leading, computeValue: { d in
if (abs(width - d.width) > g.size.width)
{
width = 0
height -= d.height
}
let result = width
if tag == self.tags.last! {
width = 0 //last item
} else {
width -= d.width
}
return result
})
.alignmentGuide(.top, computeValue: {d in
let result = height
if tag == self.tags.last! {
height = 0 // last item
}
return result
})
}
}.background(viewHeightReader($totalHeight))
}
private func item(for text: String) -> some View {
Text(text)
.padding(.all, 5)
.font(.body)
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(5)
}
private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
return GeometryReader { geometry -> Color in
let rect = geometry.frame(in: .local)
DispatchQueue.main.async {
binding.wrappedValue = rect.size.height
}
return .clear
}
}
}
struct HashTagView_Previews: PreviewProvider {
static var previews: some View {
HashTagView()
}
}

Align Views by constraints

I would like to build a view similar to this
✓ **Title Text**
Description Text
Where the icon an the title text have the same horizontal center ant the title text and the description text have the same alginment at the left.
Since i could not find any possiblity in SwiftUI to set constraints I am a little bit stuck.
The best solution i could come up was this
HStack(alignment: .top, spacing: Constants.Stacks.defaultHorizontalSpacing) {
challengeTask.status.getIconImage()
VStack(alignment: .leading, spacing: Constants.Stacks.defaultVerticalSpacing) {
Text(challengeTask.title)
.titleText()
Text(challengeTask.description)
.multilineTextAlignment(.leading)
.descriptionText()
Spacer()
}
}
But this does not align the icon horiztontally with the title text
iOS 16
struct ContentView: View {
var body: some View {
HStack(alignment: .firstTextBaseline) {
// ^^^^^^^^^^^^^^^^^
Image(systemName: "checkmark")
VStack {
Text("Title").font(.title.bold())
Text("Content").multilineTextAlignment(.leading)
}
}
}
}
Using hidden
struct ContentView: View {
var body: some View {
VStack {
HStack {
iconImage()
Text("Title").font(.title.bold())
}
HStack {
iconImage().hidden()
Text("Content").multilineTextAlignment(.leading)
}
}
}
private func iconImage() -> some View {
// Change it to your image
Image(systemName: "checkmark")
}
}
Using GeometryReader
struct ContentView: View {
#State private var iconSize: CGFloat = .zero
var body: some View {
VStack {
HStack(spacing: 10) {
Image(systemName: "checkmark")
.readSize { iconSize = $0.width }
Text("Title")
.font(.title.bold())
}
Text("Content")
.padding(.leading, iconSize + 10)
}
}
}
fileprivate struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { }
}
extension View {
func readSize(onChange: #escaping (CGSize) -> Void) -> some View {
modifier(ReadSize(onChange))
}
}
fileprivate struct ReadSize: ViewModifier {
let onChange: (CGSize) -> Void
init(_ onChange: #escaping (CGSize) -> Void) {
self.onChange = onChange
}
func body(content: Content) -> some View {
content.background(
GeometryReader { geometryProxy in
Color.clear.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { }
}
}
Hope this help!
I think the right way to deal with this is using a custom alignment as described here.
In your case you have 2 possibilities depending on how you want to implement the UI hierarchy:
Align image center with title center
Align description leading with title leading
Playground for both versions:
import SwiftUI
import PlaygroundSupport
extension HorizontalAlignment {
private struct TitleAndDescriptionAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
context[HorizontalAlignment.center]
}
}
static let titleAndDescriptionAlignmentGuide = HorizontalAlignment(
TitleAndDescriptionAlignment.self
)
}
extension VerticalAlignment {
private struct ImageAndTitleCenterAlignment: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
context[VerticalAlignment.center]
}
}
static let imageAndTitleCenterAlignmentGuide = VerticalAlignment(
ImageAndTitleCenterAlignment.self
)
}
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
VStack(alignment: .titleAndDescriptionAlignmentGuide) {
HStack {
Image(systemName: "rosette")
Text("Title text")
.font(.largeTitle)
.alignmentGuide(.titleAndDescriptionAlignmentGuide) { context in
context[.leading]
}
}
Text("Description text")
.alignmentGuide(.titleAndDescriptionAlignmentGuide) { context in
context[.leading]
}
}
HStack(alignment: .imageAndTitleCenterAlignmentGuide) {
Image(systemName: "rosette")
.alignmentGuide(.imageAndTitleCenterAlignmentGuide) { context in
context[VerticalAlignment.center]
}
VStack(alignment: .leading) {
Text("Title text")
.font(.largeTitle)
.alignmentGuide(.imageAndTitleCenterAlignmentGuide) { context in
context[VerticalAlignment.center]
}
Text("Description text")
}
}
}
}
}
}
PlaygroundPage.current.setLiveView(ContentView())

Choppy scrolling with ScrollView when updating View while scrolling SwiftUI

I am using my own ScrollView which has scroll start and end callbacks, so that I can perform some actions based on them, like hiding/showing a banner.
Here's my code for ScrollView
struct TrackableScrollView<Content>: View where Content: View {
private let onScrollingStarted: () -> Void
private let onScrollingFinished: () -> Void
#State var scrollViewHelper = ScrollViewHelper()
let content: Content
public init(#ViewBuilder content: () -> Content,
onScrollingStarted: #escaping () -> Void = {},
onScrollingFinished: #escaping () -> Void = {}) {
self.content = content()
self.onScrollingStarted = onScrollingStarted
self.onScrollingFinished = onScrollingFinished
}
public var body: some View {
GeometryReader { outsideProxy in
ScrollView(.vertical, showsIndicators: true) {
ZStack(alignment: .top) {
GeometryReader { insideProxy in
Color.clear
.preference(key: ScrollOffsetPreferenceKey.self, value: [self.calculateContentOffset(fromOutsideProxy: outsideProxy, insideProxy: insideProxy)])
}
self.content
}
}
.onPreferenceChange(ScrollOffsetPreferenceKey.self) { value in
scrollViewHelper.currentOffset = value[0]
}
.simultaneousGesture(
DragGesture().onChanged { _ in
onScrollingStarted()
}
)
.onReceive(scrollViewHelper.$offsetAtScrollEnd) { _ in
onScrollingFinished()
}
}
}
private func calculateContentOffset(fromOutsideProxy outsideProxy: GeometryProxy, insideProxy: GeometryProxy) -> CGFloat {
return outsideProxy.frame(in: .global).minY - insideProxy.frame(in: .global).minY
}
}
private struct ScrollOffsetPreferenceKey: PreferenceKey {
typealias Value = [CGFloat]
static var defaultValue: [CGFloat] = [0]
static func reduce(value: inout [CGFloat], nextValue: () -> [CGFloat]) {
value.append(contentsOf: nextValue())
}
}
class ScrollViewHelper: ObservableObject {
#Published var currentOffset: CGFloat = 0
#Published var offsetAtScrollEnd: CGFloat = 0
private var cancellable: AnyCancellable?
init() {
cancellable = AnyCancellable($currentOffset
.debounce(for: 0.3, scheduler: DispatchQueue.main)
.dropFirst()
.assign(to: \.offsetAtScrollEnd, on: self))
}
}
And here's my code to show some content
struct ContentView: View {
#State var messageBannerVisisbility: Bool = false
var body: some View {
VStack {
TrackableScrollView {
VStack(alignment: .center, spacing: 0) {
ForEach(0...100, id: \.self) { i in
Rectangle()
.frame(width: 200, height: 100)
.foregroundColor(.green)
.overlay(Text("\(i)"))
.padding()
}
}
} onScrollingStarted: {
hideMessageBanner()
} onScrollingFinished: {
showMessageBanner()
}
if messageBannerVisisbility {
Rectangle()
.frame(height: 100)
.foregroundColor(.red)
.overlay(Text("Random bottom view"))
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
.navigationBarHidden(true)
.onAppear {
showMessageBanner()
}
}
}
I am toggling messageBannerVisisbility with animation inside showMessageBanner() function.
If I keep below code, scrolling is not smooth. Could it be because I am showing/hiding the banner with animation on scroll callbacks? I guess I can just update the banner, instead of the whole View, but I am not sure how can I achieve that!
if messageBannerVisisbility {
Rectangle()
.frame(height: 100)
.foregroundColor(.red)
.overlay(Text("Random bottom view"))
.transition(.move(edge: .bottom).combined(with: .opacity))
}
What could I do to improve scrolling experience? My app does support iOS 13, but I am also fine with implementing 2 different solutions, one for iOS 13 and other one for iOS 14 and above, if that makes life a little easier!

How to make SwiftUI Grid lay out evenly based on width?

I'm trying to use a SwiftUI Lazy Grid to lay out views with strings of varying lengths. How can I construct my code so that, e.g. if 3 view's do not fit, it will only make 2 columns and push the 3rd view to the next row so that they won't overlap?
struct ContentView: View {
var data = [
"Beatles",
"Pearl Jam",
"REM",
"Guns n Roses",
"Red Hot Chili Peppers",
"No Doubt",
"Nirvana",
"Tom Petty and the Heart Breakers",
"The Eagles"
]
var columns: [GridItem] = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
LazyVGrid(columns: columns, alignment: .center) {
ForEach(data, id: \.self) { bandName in
Text(bandName)
.fixedSize(horizontal: true, vertical: false)
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You can use this method to achieve what you're looking for, solution source: https://www.fivestars.blog/articles/flexible-swiftui/
ContentView
struct ContentView: View {
// MARK: - PROPERTIES
var data = [
"Beatles",
"Pearl Jam",
"REM",
"Guns n Roses",
"Red Hot Chili Peppers",
"No Doubt",
"Nirvana",
"Tom Petty and the Heart Breakers",
"The Eagles"
]
// MARK: - BODY
var body: some View {
FlexibleView(
availableWidth: UIScreen.main.bounds.width, data: data,
spacing: 15,
alignment: .leading
) { item in
Text(verbatim: item)
.padding(8)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(Color.gray.opacity(0.2))
)
}
.padding(.horizontal, 10)
}
}
// MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
FlexibleView
// MARK: - FLEXIBLE VIEW
struct FlexibleView<Data: Collection, Content: View>: View where Data.Element: Hashable {
let availableWidth: CGFloat
let data: Data
let spacing: CGFloat
let alignment: HorizontalAlignment
let content: (Data.Element) -> Content
#State var elementsSize: [Data.Element: CGSize] = [:]
var body : some View {
VStack(alignment: alignment, spacing: spacing) {
ForEach(computeRows(), id: \.self) { rowElements in
HStack(spacing: spacing) {
ForEach(rowElements, id: \.self) { element in
content(element)
.fixedSize()
.readSize { size in
elementsSize[element] = size
}
}
}
}
}
}
func computeRows() -> [[Data.Element]] {
var rows: [[Data.Element]] = [[]]
var currentRow = 0
var remainingWidth = availableWidth
for element in data {
let elementSize = elementsSize[element, default: CGSize(width: availableWidth, height: 1)]
if remainingWidth - (elementSize.width + spacing) >= 0 {
rows[currentRow].append(element)
} else {
currentRow = currentRow + 1
rows.append([element])
remainingWidth = availableWidth
}
remainingWidth = remainingWidth - (elementSize.width + spacing)
}
return rows
}
}
View Extension
// MARK: - EXTENSION
extension View {
func readSize(onChange: #escaping (CGSize) -> Void) -> some View {
background(
GeometryReader { geometryProxy in
Color.clear
.preference(key: SizePreferenceKey.self, value: geometryProxy.size)
}
)
.onPreferenceChange(SizePreferenceKey.self, perform: onChange)
}
}
private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

SwiftUI - Expanding the main grid horizontally pushes my other views offscreen

I am working on an iPhone app using SwiftUI. The main grid uses HStacks nested inside a VStack. The number of columns will be variable on initialization, but fixed thereafter. The number of rows is completely dynamic. When the grid expands beyond the width or height of the screen it pushes the other views out of the way.
I would like it to just expand rightward (on initialization) and downward (dynamically) offscreen and behind the other views. I tried putting everything in a ZStack and setting their zindices, but that didn't work. Is there any way to do this or do I need a new approach?
//
// GameView.swift
// Scoreboard
//
// Created by user926153 on 8/21/20.
// Copyright © 2020 user926153. All rights reserved.
//
//
//
/*
This uses the TrackableScrollView as created by Max Natchanon here:
https://medium.com/#maxnatchanon/swiftui-how-to-get-content-offset-from-scrollview-5ce1f84603ec
*/
import SwiftUI
import UIKit
struct ScrollOffsetPreferenceKey: PreferenceKey {
typealias Value = [CGFloat]
static var defaultValue: [CGFloat] = [0]
static func reduce(value: inout [CGFloat], nextValue: () -> [CGFloat]) {
value.append(contentsOf: nextValue())
}
}
struct TrackableScrollView<Content>: View where Content: View {
let axes: Axis.Set
let showIndicators: Bool
#Binding var contentOffset: CGFloat
let content: Content
init(_ axes: Axis.Set = .vertical, showIndicators: Bool = true, contentOffset: Binding<CGFloat>, #ViewBuilder content: () -> Content) {
self.axes = axes
self.showIndicators = showIndicators
self._contentOffset = contentOffset
self.content = content()
}
var body: some View {
GeometryReader { outsideProxy in
ScrollView(self.axes, showsIndicators: self.showIndicators) {
ZStack(alignment: self.axes == .vertical ? .top : .leading) {
GeometryReader { insideProxy in
Color.clear
.preference(key: ScrollOffsetPreferenceKey.self, value: [self.calculateContentOffset(fromOutsideProxy: outsideProxy, insideProxy: insideProxy)])
// Send value to the parent
}
VStack {
self.content
}
}
}
.onPreferenceChange(ScrollOffsetPreferenceKey.self) { value in
self.contentOffset = value[0]
}
// Get the value then assign to offset binding
}
}
private func calculateContentOffset(fromOutsideProxy outsideProxy: GeometryProxy, insideProxy: GeometryProxy) -> CGFloat {
if axes == .vertical {
return (outsideProxy.frame(in: .global).minY - insideProxy.frame(in: .global).minY) * -1
} else {
return (outsideProxy.frame(in: .global).minX - insideProxy.frame(in: .global).minX) * -1
}
}
}
struct GameView: View {
let row_label_offset: CGFloat = 80
let col_width: CGFloat = 75
let row_height: CGFloat = 50
#ObservedObject var settings: GameSettings
#State var round_number: Int = 1
#State var scores: [[Int]] = [[0, 0, 0, 0]]
#State var column_offset: CGFloat = 0
#State var row_offset: CGFloat = 0
private func AddRound() {
self.round_number += 1
self.scores.append([0, 0, 0, 0])
}
private func DeleteRound(at offsets: IndexSet) {
// NOTE: also have to delete round from score array
self.round_number -= 1
self.scores.remove(atOffsets: offsets)
}
var body: some View {
VStack {
VStack(alignment: .center, spacing: 10) {
Text("Title")
.font(.title)
Text("subtitle")
}
.border(Color.black)
VStack(alignment: .leading, spacing: 10) {
HStack {
Button(action: {
self.AddRound()
}) {
Text("New round +")
.fixedSize(horizontal: false, vertical: true)
}
.frame(width: self.row_label_offset, height: self.row_height)
TrackableScrollView(.horizontal, showIndicators: false, contentOffset: $column_offset) {
HStack {
ForEach((1...7), id: \.self) {
Text("Player \($0)\n total")
.frame(width: self.col_width, height: self.row_height)
}
}
}
.frame(height: 50)
.border(Color.red)
}
HStack {
TrackableScrollView(.vertical, showIndicators: false, contentOffset: $row_offset) {
ForEach((1...self.round_number), id: \.self) { round in
Text("Round \(round)")
.frame(width: self.col_width, height: self.row_height)
}
}
.border(Color.black)
.frame(width: self.row_label_offset)
VStack {
ForEach(self.scores, id: \.self) { round_score in
HStack {
ForEach(round_score, id: \.self) { score in
Text("\(score)")
.frame(width: self.col_width, height: self.row_height)
}
}
}
Spacer()
}
.offset(x: self.column_offset, y: self.row_offset)
Spacer()
}
.border(Color.blue)
}
Button(action: {
}) {
Text("Finish Game")
}
Spacer()
}
}
}
#if DEBUG
struct GameView_Previews: PreviewProvider {
static var previews: some View {
GameView(settings: GameSettings())
}
}
#endif
Here is fixed part - to avoid layout corruption you have to move dynamic part out-of-current-layout, eg. in overlay of empty space area. Also some minor fixes added, like clipping and alignment.
Tested with Xcode 12 / iOS 14
HStack {
TrackableScrollView(.vertical, showIndicators: false, contentOffset: $row_offset) {
ForEach((1...self.round_number), id: \.self) { round in
Text("Round \(round)")
.frame(width: self.col_width, height: self.row_height)
}
}
.border(Color.black)
.frame(width: self.row_label_offset)
Color.clear.overlay ( // << from here !!
VStack {
ForEach(self.scores, id: \.self) { round_score in
HStack {
ForEach(round_score, id: \.self) { score in
Text("\(score)")
.frame(width: self.col_width, height: self.row_height)
}
}
}
Spacer()
}
.offset(x: self.column_offset, y: self.row_offset)
, alignment: .topLeading)
.clipped()
}
.border(Color.blue)
}

Resources