Ameen MK Ameen MK - 1 month ago 7
Swift Question

Add text of UILabel from database by loop - Swift 3

I'm creating

UILabel
by
for
loop and I wanna adding text in the
UILabel
from database, the text in database a
String
but I'm converting
String
to
Array Characters
, for example I've 4 labels and 4 characters (A, B, C, D), I want to add each characters in one label how can I do that ??

I wanna create like this :

enter image description here

And this my code :

func createTarget(id: Int) {

listdata = dbHelpr.getDatabase(rowId: id)
var targetHeigt = CGFloat()
let viewWidth = self.view.frame.size.width

if viewWidth == 320 {
targetHeigt = 2.5
} else {
targetHeigt = 5
}

for data in listdata { // listdata is (Database) has a variable (ans)
let yAxis : CGFloat = (self.view.frame.height) * 60%
let i = data.ans.length
// char count
let width: Int = Int(view.frame.size.width) - 40
// frame width
var targetWidth: Int = (width - (i - 1) * 5) / i
if targetWidth > 50 {
targetWidth = 50
}

let totalWidth: Int = (targetWidth * i) + ((i - 1) * 5)

for x in 0..<i {
let currentWidth: Int = (width / 2) - (totalWidth / 2) + (x * targetWidth) + (x * 5) + 20
let targetLabel = UILabel(frame: CGRect(x: CGFloat(currentWidth), y: yAxis, width: CGFloat(targetWidth), height: 50))
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.textAlignment = .center
targetLabel.textColor = .black

for tar in data.ans.characters {
targetLabel.text = String(tar)
}

self.view.addSubview(targetLabel)
}
}
}


When I run my code above show me this :

enter image description here


My output :

D


D


D


D



And when I edited and added my code to :

for data in listdata { // listdata is (Database) has a variable (ans)

let tar = data.ans.characters.map{String($0)}

lblLabel.text = tar.joined(separator: " ")

}


This a result of my code above :

enter image description here


My output :

D C B A


D C B A


D C B A


D C B A



What's the best solve to create label whit characters exactly like 1st picture ??

Answer Source

You're already creating one label for each character, so there is no need to loop over them again.

Try this:

for (x, tar) in data.ans.characters.reversed().enumerated() {
    let currentWidth: Int = (width / 2) - (totalWidth / 2) + (x * targetWidth) + (x * 5) + 20
    let targetLabel = UILabel(frame: CGRect(x: CGFloat(currentWidth), y: yAxis, width: CGFloat(targetWidth), height: 50))
    targetLabel.backgroundColor = .white
    targetLabel.layer.masksToBounds = true
    targetLabel.layer.cornerRadius = 5
    targetLabel.textAlignment = .center
    targetLabel.textColor = .black

    targetLabel.text = String(tar)

    self.view.addSubview(targetLabel)
}