1

So this is kind of a weird one, and I don't quite understand what is going on...

So I've made a few custom classes/objects (UIViews) within each other like this:

class Example1: UIView {
    [properties etc.]

let Test = Example2()
Test.frame = CGRe...
addSubview(Test)
} 


class Example2: UIView {
    [properties etc.]
} 

This all works fine until you add some sort of function to Example2. Then it will run everything multiple times (if you call Example1, Example2 = 1, 2 it will run in this order: 1, 1, 2, 2, 1, 2, 1, 2, 2, 2 ).

The problem with this is that it will create multiple versions of the same object, but with different values as they are calculated somewhere else (the size and position etc.).

I hope I was able to explain my problem like this, otherwise is the entire (quite messy since I've been trying to solve this for a while) code: http://pastebin.com/4D3kt1uN (if you,like you can try and run it in xcode to see what i mean).

Any help is greatly appreciated!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Mats
  • 359
  • 2
  • 6
  • 13
  • The problem is that your code is in `layoutSubviews`, which can (and generally will) be called multiple times. Each time, your code creates and adds new subviews (each of which will receive `layoutSubviews` calls). You should **create** the subviews in the initialiser for the class; `layoutSubviews` should then ensure they are in the right place. – pbasdf Feb 27 '16 at 12:07
  • @pbasdf This fixes the problem with it running multiple times, but what am i supposed to use as initialiser/constructor? I've tried required init coder and frame but then it will only execute the first class (or none)... – Mats Feb 27 '16 at 14:39
  • Where you have, for example, `let monday = RoosterViewMonday()`, the `init()` method is called (not `init(frame:)` or `init(coder:)`). Either amend to use `let monday = RoosterViewMonday(frame: ....)` or implement `init()`. Likewise for the other Rooster... views. – pbasdf Feb 28 '16 at 16:46

1 Answers1

0

The problem with your code is that you are adding subview in layoutSubviews method.

override func layoutSubviews() {
    ...
    let GuideLine = UIView()
    addSubview(GuideLine)
    ...
}

The layoutSubviews method can be called many times during application's lifetime. See, for example, this SO question "When is layoutSubviews called?". As the result your subviews get added to the screen every time whenever layout changes. That is why you see multiple versions of your views. Try moving your logic out of the layoutSubviews method.

Community
  • 1
  • 1
euvs
  • 1,595
  • 13
  • 13
  • This fixes the problem with it running multiple times, but what am i supposed to use as initialiser/constructor? I've tried required init coder and frame but then it will only execute the first class (or none)... – Mats Feb 27 '16 at 14:38