Interface Builder,@ IBOutlet以及Swift中delegate和dataSource的协议

Dmi*_*try 27 interface-builder iboutlet swift

无法将CustomView声明为@IBOutlet的委托属性连接到ViewControllerInterface Builder中 - 根本无法建立连接.

这是代码

class CustomView: UIView {
     @IBOutlet var delegate: CustomViewDelegate?
}

@objc protocol CustomViewDelegate {
     ...
}


class ViewController: UIViewController, CustomViewDelegate {
     ...
}
Run Code Online (Sandbox Code Playgroud)

@objc因为swift协议使用,IBOutlet属性不能有非对象类型,不知道为什么protocol CustomViewDelegate: class {}不起作用.

还有其他人遇到过类似的东西吗?

mat*_*att 58

来自Xcode发行说明:

当插座的类型是协议时,Interface Builder不支持连接到Swift文件中的插座.

解决方法:将插座的类型声明为AnyObject或NSObject,使用Interface Builder将对象连接到插座,然后将插座的类型更改回协议.

编辑: Xcode 9 beta 3发行说明说不再需要这种解决方法.

  • Wowzer!这很有效,谢谢.Apple ...请一起来吧! (3认同)

Lar*_*erg 16

Adam Waite提供了一个很好的解决方法.然而,我更喜欢以下解决方案,因为它强调了解决方法,并且一旦Xcode得到修复,也可以轻松删除额外属性.

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 {
    ...
}
Run Code Online (Sandbox Code Playgroud)

嘿,这个小虫已经有一年半了吗?


Wen*_*aoD 9

优雅的解决方法:

#if TARGET_INTERFACE_BUILDER
@IBOutlet open weak var delegate: AnyObject?
#else
open weak var delegate: CustomViewDelegate?
#endif
Run Code Online (Sandbox Code Playgroud)

请参阅:https: //github.com/WenchaoD/FSPagerView/blob/master/Sources/FSPagerView.swift#L88


Ada*_*ite 8

另一个不漂亮但是:

@IBOutlet weak var ibDelegate: NSObject?
@IBOutlet weak var ibDataSource: NSObject?
var delegate: MultipleButtonViewDelegate? { return ibDelegate as? MultipleButtonViewDelegate }
var dataSource: MultipleButtonViewDataSource? { return ibDataSource as? MultipleButtonViewDataSource }
Run Code Online (Sandbox Code Playgroud)