6

I'm trying to call a method by extending one of my custom UIViews, but I get the error "Value of type 'MyCustomView' has no member 'testMethod'". Below is my code

extension MyCustomView {
  func testMethod() {
    //do stuff here
  }
}

//in a separate class from the extension 
class func onMoreOptionsButtonPressed(currentViewController:UIViewController) {
  for view in currentViewController.view.subviews {
    if view.isKindOfClass(MyCustomView) {
      let myCustomView = view as! MyCustomView
      myCustomView.testMethod()
    }
  }
}

Obviously I could implement this functionality a bunch of different ways, but I'm more interested in why specifically this code won't compile, because it seems logically correct to me. All help is greatly appreciated.

Amloelxer
  • 752
  • 2
  • 8
  • 20
  • Your code compiles fine for me other than the missing `}` – dan Jul 21 '16 at 18:08
  • Fixed the brace thank you. That's what so weird about it. I tried deleting derived data, and quitting Xcode and restarting, but it still won't compile. It must be something with the existing architecture then right @dan? – Amloelxer Jul 21 '16 at 19:11
  • Moving the extension from its own separate file to the same class as MyCustomView solves the issue, but it's not something I would prefer to do architecturally, and unfortunately still doesn't answer my question of why it won't compile in the first place. – Amloelxer Jul 21 '16 at 20:21
  • 1
    It appears that extensions can only be used in the file they're created in (http://stackoverflow.com/questions/24133297/using-extensions-in-separate-swift-file). I'm not sure this is necessarily true, but this question might help you. – Wyetro Jul 21 '16 at 22:50

2 Answers2

0

This may have something to do with the fact that UIView is an Objective-C class and method dispatching differs slightly with pure Swift classes.

You may have to declare the extension's method with the dynamic directive to satisfy the method dispatch mechanism of Obj-C.

(I haven't tried it mind you)

Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

The only answer I can think of is that your extension file is not member of the target you are compiling. Select the file that has the extension code and take a look at Target Membership in the file inspector, make sure your target is checked. If the file is not inside the project folders, you might have to move it there to see the Target Membership section.

Lio
  • 4,225
  • 4
  • 33
  • 40