Last active
June 5, 2022 07:13
-
-
Save VladimirFibe/61debbcbf77298d73ddbb50ba7a4344e to your computer and use it in GitHub Desktop.
Plus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct TextPlus: View { | |
var platforms: [String] | |
let font = UIFont.systemFont(ofSize: 12, weight: .regular) | |
var body: some View { | |
GeometryReader { gr in | |
content(gr: gr) | |
} | |
} | |
func content(gr: GeometryProxy) -> some View { | |
var result = 0 | |
let count = platforms.count | |
var index = 0 | |
var end: Int { | |
count - result - 1 | |
} | |
var width = CGFloat.zero | |
repeat { | |
let word = platforms[index].widthOfString(usingFont: font) + 22 | |
if width + word < gr.size.width { | |
result = index | |
index += 1 | |
width += word | |
} else { | |
index = count | |
} | |
} while index<count | |
if result < count - 1 { | |
let pluswidth = "+\(end)".widthOfString(usingFont: font) + 22 | |
if width + pluswidth < gr.size.width { | |
result -= 1 | |
} | |
} | |
return HStack(spacing: 0) { | |
ForEach(0...result, id: \.self) { index in | |
GradientRoundedTextView(text: platforms[index]) | |
.padding(4) | |
} | |
if count - result - 1 > 0 { | |
GradientRoundedTextView(text: "+\(count - result - 1)") | |
.padding(4) | |
} | |
} | |
} | |
} | |
struct GradientRoundedTextView: View { | |
var text: String | |
var body: some View { | |
HStack { | |
Text(text) | |
.font(.system(size: 12, weight: .regular)) | |
.foregroundColor(.white) | |
.padding(.horizontal, 7) | |
}.frame(height: 24) | |
.background(Color.green) | |
.cornerRadius(16) | |
} | |
} | |
extension String { | |
func widthOfString(usingFont font: UIFont) -> CGFloat { | |
let fontAttributes = [NSAttributedString.Key.font: font] | |
let size = self.size(withAttributes: fontAttributes) | |
return size.width | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment