Reputation: 415
In my app I have an array coming back from an API and currently it is creating a new label for each item and stacking them one on top of another. I would like it to create one label where the array items are in string separated by a bullet. Here is my current working code:
lblLeft.text = ""
if let expertiseCount = helper.expertise {
for i in 0..<expertiseCount.count {
if i >= 0 {
print(expertiseCount[i].name!)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
let attrString = NSMutableAttributedString(string: lblLeft.text! + "\(expertiseCount[i].name ?? "")\n")
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range: NSMakeRange(0, attrString.length))
lblLeft.attributedText = attrString
}
}
}
currently looks like the image on the left, I want it to look like the image on the right.
Upvotes: 2
Views: 1843
Reputation: 880
Swift 5
if you want to set a single string to a label in loop, you can follow this simple method.
for hash in objSinglePost?.hash_tags ?? [Hashtags].init() {
self.lblHashtags.text = (self.lblHashtags.text ?? "") + " #" + (hash.hash_tags ?? "")
}
Upvotes: 0
Reputation: 1112
I'd change your code like this:
if let expertise = helper.expertise {
let expertises = expertise.joined(" • ") // join the strings with bullet point char
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
paragraphStyle.lineBreakMode = .byWordWrapping // line break by word wrappnig
let attrString = NSMutableAttributedString(string: expertises)
attrString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: 0..<attrString.characters.count) // not sure i this range will work, change to fit your needs
lblLeft.attributedText = attrString
}
This code wasn't tested but you got the idea...
Upvotes: 0
Reputation: 20804
Taking in account that your Expertise
class .name
is what you need to concat, you can use map
and after that as @Andrii answer suggest use join
and finally adjusting the paragraphStyle.lineBreakMode
, replace your code by this one
if let expertiseCount = helper.expertise {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10
paragraphStyle.lineBreakMode = .byWordWrapping
let finalString = expertiseCount.map({$0.name}).joined(separator: " • ")
let finalAttributedString = NSMutableAttributedString(string: finalString, attributes: [NSParagraphStyleAttributeName:paragraphStyle])
lblLeft.attributedText = finalAttributedString
}
Hope this helps
Upvotes: 2
Reputation: 10194
You don't need to loop over your expertiseCount
array. Arrays of strings in Swift have a special method joined(separator:)
, which should do exactly what you need:
let joinedExpertise = expertiseCount.joined(" • ")
Use a special bullet point character, •
, as a separator.
Upvotes: 3