Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active December 23, 2019 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/6f5f458aa35d375ebd2fe2d87f2698ce to your computer and use it in GitHub Desktop.
Save chriseidhof/6f5f458aa35d375ebd2fe2d87f2698ce to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// Bars
//
// Created by Chris Eidhof on 17.12.19.
// Copyright © 2019 objc.io. All rights reserved.
//
import SwiftUI
struct SignalStrengthView: View {
var rssi: Double = -75
var body: some View {
HStack {
Text("NNNNN").overlay(
SignalStrengthIndicator(bars: 2)
)
Text("\(self.rssi, specifier: "%.0f") dB")
// Change the font to size the text. The bar chart should resize accordingly.
}.font(.largeTitle)
}
}
struct Divided<S: Shape>: Shape {
var nested: S
var amount: CGFloat // 0...1
func path(in rect: CGRect) -> Path {
let newRect = rect.divided(atDistance: rect.height * amount, from: .maxYEdge).slice
return nested.path(in: newRect)
}
}
struct SignalStrengthIndicator: View {
var bars: Int
var totalBars: Int = 5
var body: some View {
HStack {
ForEach(0..<totalBars) { ix in
Divided(
nested: RoundedRectangle(cornerRadius: 5),
amount: CGFloat(ix + 1)/CGFloat(self.totalBars)
)
.fill(ix < self.bars ? Color.gray : Color.black)
}
}.background(Color.white)
}
}
struct ContentView: View {
var body: some View {
SignalStrengthView()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@luckychris
Copy link

little improvement suggestion:

struct SignalStrengthIndicator: View {
var bars: Int
var totalBars: Int = 5

var body: some View {
    GeometryReader() { proxy in
        HStack(spacing: 0.1 * proxy.size.width / CGFloat(self.totalBars)) {
            ForEach(0..<self.totalBars) { ix in
                Divided(
                    nested: RoundedRectangle(cornerRadius: 4),
                    amount: CGFloat(ix + 1)/CGFloat(self.totalBars)
                )
                    .fill(ix < self.bars ? Color.gray : Color.black)
            }
        }.background(Color.white)
    }
}

}

with this change the spacing between the bars is a bit nicer if you change the font size....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment