Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created June 11, 2020 18:14
Show Gist options
  • Save azamsharp/f76c073493a1b7503cb254bda07b1c56 to your computer and use it in GitHub Desktop.
Save azamsharp/f76c073493a1b7503cb254bda07b1c56 to your computer and use it in GitHub Desktop.
ContentView.swift
//
// Array+Extensions.swift
// GridSwiftUI
//
// Created by Mohammad Azam on 6/11/20.
// Copyright Β© 2020 Mohammad Azam. All rights reserved.
//
import Foundation
extension Array {
func chunks(size: Int) -> [ArraySlice<Element>] {
var chunks: [ArraySlice<Element>] = [ArraySlice<Element>]()
for index in stride(from: 0, to: self.count - 1, by: size) {
var chunk = ArraySlice<Element>()
let end = index + size
if end >= self.count {
chunk = self[index..<self.count]
} else {
chunk = self[index..<end]
}
chunks.append(chunk)
if (end + 1) == self.count {
let remainingChunk = self[end..<self.count]
chunks.append(remainingChunk)
}
}
return chunks
}
}
//
// ContentView.swift
// GridSwiftUI
//
// Created by Mohammad Azam on 6/11/20.
// Copyright Β© 2020 Mohammad Azam. All rights reserved.
//
import SwiftUI
struct ContentView: View {
let animals = ["🐈","πŸ†","🦌","πŸ¦’","🦏","πŸ„","πŸ€","🦩","🦜"]
@State private var sliderValue: CGFloat = 1
var body: some View {
NavigationView {
VStack {
Slider(value: $sliderValue, in: 1...8, step: 1)
Text(String(format: "%.0f", self.sliderValue))
.font(.system(size: 20))
.fontWeight(.bold)
.padding()
.background(Color.purple)
.foregroundColor(Color.white)
.clipShape(Circle())
List(self.animals.chunks(size: Int(self.sliderValue)), id: \.self) { chunk in
ForEach(chunk, id: \.self) { animal in
Text(animal)
.font(.system(size: CGFloat(300/self.sliderValue)))
}
}
}
.navigationBarTitle("Animals")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment