Skip to content

Instantly share code, notes, and snippets.

@chriseidhof chriseidhof/bars.swift

Last active Dec 23, 2019
Embed
What would you like to do?
//
// 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

This comment has been minimized.

Copy link

luckychris commented Dec 23, 2019

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
You can’t perform that action at this time.