Ivan
Ivan

Reputation: 43

Swift isKindOfClass not work

I have a ViewController and some label and textfield for user to input, and in some point I need to loop over all textfield to collect the user's input.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.configureView()
   for views in self.view.subviews        {
        if view is UITextField
        {
            println("inside")
        }
        println(views.description)

    }
}

For this code, the "inside" never print out. But I do see some the information of views.description

   <UILabel: 0x7fa4b1c7bd00; frame = (16 97; 76 21); text = 'FromDate';        opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer =           <_UILabelLayer: 0x7fa4b1c44580>>
  <UILabel: 0x7fa4b1c9fd60; frame = (16 169; 82 21); text = 'ControlNO'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fa4b1c77fb0>>

>

   <UITextField: 0x7fa4b1c7a050; frame = (106 95; 197 30); text = ''; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7fa4b1c6c800>>

  <UITextField: 0x7fa4b1c9c060; frame = (106 126; 197 30); text = ''; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; tag = 1; layer = <CALayer: 0x7fa4b1c9c2c0>>

   <_UILayoutGuide: 0x7fa4b1d11d20; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x7fa4b1d11e00>>
   <_UILayoutGuide: 0x7fa4b1d253f0; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x7fa4b1d12f60>>

but if I println(views.dynamicType) I could only see ExistentialMetatype.

What is wrong in my code?

Upvotes: 1

Views: 716

Answers (3)

Martin R
Martin R

Reputation: 539705

The loop variable is called views, but you test view (which is not the loop variable and therefore identical to self.view):

for views in self.view.subviews { // "views" here
    if view is UITextField {      // "view" here
        println("inside")
    }
}

If you rename the loop variable to view

for view in self.view.subviews {
    if view is UITextField {
        println("inside")
    }
}

then everything works as expected.

Upvotes: 2

keithbhunter
keithbhunter

Reputation: 12324

@Christian's code will work. Here is another solution.

if let view = tex as? UITextField {
    // view is a UITextField
}

Upvotes: 0

Christian
Christian

Reputation: 22343

You can use isKindOfClass:

var tex = UITextField()

if tex.isKindOfClass(UITextField){
    println("yes")
}

Upvotes: 0

Related Questions