Skip to content

Instantly share code, notes, and snippets.

@zrzka
Created February 12, 2020 22:02
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 zrzka/6fc706e7b750f19e19cffe416af7ce46 to your computer and use it in GitHub Desktop.
Save zrzka/6fc706e7b750f19e19cffe416af7ce46 to your computer and use it in GitHub Desktop.
import SwiftUI
struct SignalStrengthIndicator: View {
/// Spacing between individual bars.
@State var barSpacing: CGFloat = 2
/// Minimal height of a bar (`0.1` means 10% of the actual height).
@State var minBarHeight: CGFloat = 0.1
/// Individual bar corner radius.
@State var barCornerRadius: CGFloat = 8.0
/// Number of highlighted bars.
@State var bars: Int = 2
/// Total number of bars.
@State var totalBars: Int = 5
var body: some View {
HStack(spacing: barSpacing) {
ForEach(0 ..< totalBars) { idx in
RoundedRectangle(cornerRadius: self.barCornerRadius, style: .continuous)
.scale(x: 1.0, y: self.scaleY(for: idx), anchor: .bottom)
.fill(idx < self.bars ? Color.primary : Color.secondary)
}
}
}
private func scaleY(for index: Int) -> CGFloat {
guard totalBars > 1 else { return 1.0 }
return self.minBarHeight + (1.0 - minBarHeight) / .init(totalBars - 1) * .init(index)
}
}
struct SignalStrengthView: View {
var body: some View {
HStack(alignment: .center) {
SignalStrengthIndicator(bars: 2, totalBars: 5)
.aspectRatio(2.3, contentMode: .fit)
Text("-75 db")
// TODO: Would be nicer to have a dynamic padding based on the font size
.padding([.bottom, .top], 6.0)
.layoutPriority(1)
}
}
}
#if DEBUG
struct SignalStrengthIndicator_Previews: PreviewProvider {
static var previews: some View {
VStack(spacing: 30) {
HStack(spacing: 10) {
SignalStrengthIndicator(bars: 0, totalBars: 5)
.frame(width: 70, height: 30)
SignalStrengthIndicator(bars: 2, totalBars: 5)
.frame(width: 70, height: 30)
SignalStrengthIndicator(bars: 5, totalBars: 5)
.frame(width: 70, height: 30)
}
HStack(spacing: 10) {
SignalStrengthIndicator(bars: 0, totalBars: 5)
.frame(width: 70, height: 60)
SignalStrengthIndicator(bars: 2, totalBars: 5)
.frame(width: 70, height: 60)
SignalStrengthIndicator(bars: 5, totalBars: 5)
.frame(width: 70, height: 60)
}
HStack(spacing: 10) {
SignalStrengthIndicator(bars: 0, totalBars: 5)
.frame(width: 100, height: 30)
SignalStrengthIndicator(bars: 2, totalBars: 5)
.frame(width: 100, height: 30)
SignalStrengthIndicator(bars: 5, totalBars: 5)
.frame(width: 100, height: 30)
}
SignalStrengthView()
.font(.caption)
SignalStrengthView()
SignalStrengthView()
.font(.largeTitle)
Spacer()
.layoutPriority(1)
}
.padding()
}
}
#endif
@zrzka
Copy link
Author

zrzka commented Feb 12, 2020

Screen Shot 2020-02-12 at 23 05 23

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