Search code examples
swiftibactionswift-extensions

Swift @IBActions in ViewController Extension


I’ve noticed in Swift/Xcode 11 that you can’t ctrl-drag an IB object into a ViewController extension to create an IBAction, but you can cut/paste it into the ext. after ctrl-dragging to create the IBAction in the ViewController class & it works. Anything wrong w/moving an IBAction to a ViewController extension using copy and paste? And why is the Ctrl drag not working for the VC extension? I was putting UITextView actions in an ext w/other TextView funcs ‬when I noticed this but don’t fully understand why the ctrl-drag won’t work but cut/paste appears to show no prob. Thx for considering the Q.


Solution

  • Unless someone works for Apple I'm not sure we'll get an actual answer here. I can guess and give you an alternative that worked for me though.

    From an Xcode feature implementation standpoint, the code that supports these actions probably varies..

    From what I've seen control drag works when the class of the VC on the storyboard directly matches the class of the object you're dragging into.

    I've never tried dragging into extensions but I can see how that might be complicated given that stored properties are not allowed on extensions which adds complications given you can drag outlets too.

    However, I've also done IBAction/IBOutlet's on parent classes and I was able to get that to work when I started dragging FROM the an existing IBAction func (there's a circle to the left of it in the code) TO the storyboard of the child class.

    In short, I'm assuming there's a lot of assumptions and code being done to allow you to drag from storyboard onto code, and I'm pretty sure limitations are due to the complications in handling the corner cases. Apple will often opt towards not allowing behavior at all if the possibility for a broken corner case exists. Some of the other ways of creating these connections (like a copy and paste) are prob simpler.