I have text coming from an API call. I want to display it. The issue is as below:
Dummy data provided to run
struct SampleTypeBox: View {
var sampleType : [SampleTypeList]
VStack(alignment: .leading,spacing: 20){
HStack{
ForEach(sampleType.indices,id:\.self){sample in
Text("\(sample+1)." + "\(sampleType[sample].SampleName)")
.font(.system(size: 13))
.foregroundColor(.green)
}
}
struct SampleTypeBox_Previews: PreviewProvider {
static var previews: some View {
let SampleList =
[
SampleTypeList(
TestSampleTypeId: "50",
SampleName: "2 ml Serum",
ColourCode: "#FFB500"
),
SampleTypeList(
TestSampleTypeId: "55",
SampleName: "EDTA Whole Blood",
ColourCode: "#FFB500"
),
SampleTypeList(
TestSampleTypeId: "55",
SampleName: "EDTA Whole Blood",
ColourCode: "#FFB500"),
SampleTypeList(
TestSampleTypeId: "55",
SampleName: "EDTA Whole Blood",
ColourCode: "#FFB500"),
SampleTypeList(
TestSampleTypeId: "55",
SampleName: "EDTA Whole Blood",
ColourCode: "#FFB500")
]
SampleTypeBox(sampleType: SampleList)
}
}
I have attached pic. The green shows what I am getting and the red color output is what I want.
Construct a single String
from the list of samples, and create a single Text
view with it.
Text(
sampleList.enumerated().map { "\($0 + 1). \($1.sampleName)" }.joined(separator: " ")
)
.font(.system(size: 13))
.foregroundColor(.green)
...
struct SampleTypeList {
let testSampleTypeId: String
let sampleName: String
let colourCode: String
}
let sampleList =
[
SampleTypeList(
testSampleTypeId: "50",
sampleName: "2 ml Serum",
colourCode: "#FFB500"),
SampleTypeList(
testSampleTypeId: "55",
sampleName: "EDTA Whole Blood",
colourCode: "#FFB500"),
SampleTypeList(
testSampleTypeId: "55",
sampleName: "EDTA Whole Blood",
colourCode: "#FFB500"),
SampleTypeList(
testSampleTypeId: "55",
sampleName: "EDTA Whole Blood",
colourCode: "#FFB500"),
SampleTypeList(
testSampleTypeId: "55",
sampleName: "EDTA Whole Blood",
colourCode: "#FFB500")
]
If each part of the text should have different styles (font, text color, etc), you should still use one Text
, but create a AttributedString
instead of a regular String
.