viewDidLayoutSubviews is called when label changes

2019-07-27 10:26发布

问题:

I have a label, toggle button and an animation in my code. When I press the toggle button -> animation starts , label changes. Below is my code sample.

override func viewDidLayoutSubviews() {
println("viewDidLayoutSubviews is called")
// Initial state of my animation.
     }

 @IBAction func Toggled(sender: AnyObject) {
    CallTextChange() 
   // Two different Animations        
     }

 func CallTextChange() { // Change text here}

Every time I change the text in label viewDidLayoutSubviews is called. Is there a way to stop calling it every time I change the label?

回答1:

I found the answer for my problem.

When we create UIImage by drag and dropping from the object provided by Xcode, the image is temporary placed where it was statically placed. So when animating in middle when viewDidLayoutSubviews is called the image is placed in the static place. So the UIImage has to be created programmatically.

CreateImage.image = UIImage(named: "Image.png")
CreateImage = UIImageView(frame: CGRect(x: 0, y: 0, width: CreateImage.image!.size.width/6, height: CreateImage.image!.size.height/6))
self.view.addSubview(CreateImage)


回答2:

Try to pass one boolean flag values in function



回答3:

I think when you change text of and UILabel it will change its intrinsic content size that in turn will notify the system to relayout the view hierarchy. So it seems inevitable that viewDidLayoutSubviews will be called.

Either you put a boolean flag to make your initial animation code execute once only or move your code to other place like viewDidLoad() method.