I'm making a little game and I'am having trouble updating an UILabel I created to display the current score. Every time I try to update the score label the entire screen freezes up for a split second, all the objects from the previous frame remain on the screen while the next frame is drawn on top of it with the score label not updating. This problem only occurs when I try to update the UILabel otherwise everything runs fine without any hiccups.
I read that updating an UILabel needs to be done on the main thread and have tried doing so using Dispatch.main.async but the problem still occurs. Below I posted the code which has been causing me problems.
fileprivate let scoreLabel: UILabel = {
let newLabel = UILabel()
newLabel.textAlignment = .center
newLabel.textColor = .white
newLabel.text = "0"
newLabel.translatesAutoresizingMaskIntoConstraints = false
return newLabel
}()
var score: Int = 0
fileprivate lazy var displayLink: CADisplayLink = {
let newLink = CADisplayLink(target: self, selector: #selector(update))
return newLink
}()
@objc func update() {
score += 1
//Method 1: cause screen split second screen lockup
scoreLabel.text = "\(score)" //doesn't work
//Method 2: cause screen split second screen lockup
DispatchQueue.main.async {
self.scoreLabel.text = "\(score)" //also doesn't work
self.scoreLabel.setNeedsDisplay()
}
}
func setupLayout() {
view.addSubview(scoreLabel)
NSLayoutConstraint.activate([
scoreLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
scoreLabel.centerXAnchor.contraint(equalTo: view.centerXAnchor)
])
}
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
displayLink.add(to: .main, forMode: .default)
}
This is puzzling to me because this code worked in Objective-C and Swift below version 4. Any ideas as to what I'm doing wrong?
Also this is on Swift version 4.2
UPDATE:
So I found the solution. Apparently autolayout is what was causing the problems. To solve this problem I found 2 methods:
Inside DispatchQueue.main.async, first deactivate your layout constraints. Then update your label and reactivate your layout constraints and call layoutIfNeeded().
Instead of using autolayout setup your label manually setting the label.frame with a CGRect and the position using label.center and a CGPoint. After that you should be able update your label without problems.
Hopes this helps anyone else that might have ran into this problem.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)