Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface Builder, @IBOutlet and protocols for delegate and dataSource in Swift

Can't connect delegate property of CustomView declared as @IBOutlet toViewController in Interface Builder – simply can't establish a connection.

Here's the code

class CustomView: UIView {      @IBOutlet var delegate: CustomViewDelegate? }  @objc protocol CustomViewDelegate {      ... }   class ViewController: UIViewController, CustomViewDelegate {      ... } 

@objc is used because of swift protocol, IBOutlet property cannot have non-object type, don't know why protocol CustomViewDelegate: class {} doesn't work.

Anyone else came across something like that?

like image 943
Dmitry Avatar asked Oct 03 '14 13:10

Dmitry


2 Answers

From the Xcode release notes:

Interface Builder does not support connecting to an outlet in a Swift file when the outlet’s type is a protocol.

Workaround: Declare the outlet's type as AnyObject or NSObject, connect objects to the outlet using Interface Builder, then change the outlet's type back to the protocol.

EDIT: Xcode 9 beta 3 release notes say that this workaround should no longer be necessary.

like image 75
matt Avatar answered Sep 25 '22 10:09

matt


Adam Waite provides a nice workaround. I however prefer the following solution as it emphasizes the workaround and the extra property can also easily be removed once Xcode gets fixed.

class CustomView: UIView {     @IBOutlet     public var delegate: CustomViewDelegate?      /// Workaround for Xcode bug that prevents you from connecting the delegate in the storyboard.     /// Remove this extra property once Xcode gets fixed.     @IBOutlet     public var ibDelegate: AnyObject? {         get { return delegate }         set { delegate = newValue as? CustomViewDelegate }     }      func someMethod() {         // Here we always refer to `delegate`, not `ibDelegate`         delegate?.onSomethingHappened()     } }  @objc protocol CustomViewDelegate {     ... } 

Hey, is this bug already one and a half years old?

like image 36
Lars Blumberg Avatar answered Sep 22 '22 10:09

Lars Blumberg