I have a label (titleLabel) on my VC that is animated to show one letter after another until the whole string is visible. The code is as follows and is working:
titleLabel.text = ""
titleLabel.alpha = 0
var charIndex = 0.0
let titleText = "Some App Title"
for letter in titleText {
Timer.scheduledTimer(withTimeInterval: (0.1 * charIndex), repeats: false) { (timer) in
self.titleLabel.text?.append(letter)
self.titleLabel.alpha += 0.1
}
charIndex += 1
}
On smaller iPhone screens, the text adjusts its font size to fit the view during the animation. You can see the text getting smaller each time one of the final letters appears.
I have a replica of the label in my VC. It is not animated. I am looking for a way to get information about this text label after it was resized by auto layout. I want to know the font size and/or scale by which that font size was reduced. I want to use those values to set the corresponding values of my titleLabel so that its font size doesn't shrink during the animation. I have not as yet been able to set these properties programatically.
How can I accomplish this?
You can calculate font size according to the text and width of the label.
titleLabel.text = ""
titleLabel.alpha = 0
var charIndex = 0.0
let titleText = "Some App Title"
//You can use your custom font here.
titleLabel.font = UIFont.systemFont(ofSize: self.calculateOptimalFontSize(textLength: CGFloat(titleText.count), boundingBox: self.titleLabel.bounds))
for letter in titleText
{
Timer.scheduledTimer(withTimeInterval: (0.1 * charIndex), repeats: false)
{ (timer) in
self.titleLabel.text?.append(letter)
self.titleLabel.alpha += 0.1
}
charIndex += 1
}
You can create a similar function or extension.
func calculateOptimalFontSize(textLength:CGFloat, boundingBox:CGRect) -> CGFloat
{
let area:CGFloat = boundingBox.width * boundingBox.height
return sqrt(area / textLength)
}