Search code examples
iosswiftselectorobjective-c-runtimemethod-swizzling

Method swizzling for property in swift


While it is possible to replace setMyProperty: method in obj-c, I'm wondering how to do it in swift?

For example I want to replace UIScrollView::setContentOffset::

let originalSelector: Selector = #selector(UIScrollView.setContentOffset)
let replaceSelector: Selector = #selector(UIScrollView.setContentOffsetHacked)
...

...but after execution originalSelector contains setContentOffset:animaed. So, how to pass setter method of property to selector?


Solution

  • Starting from Swift 2.3 (XCode 8) it's possible to assign setter and getter to selector variable:

    The Objective-C selectors for the getter or setter of a property can now be referenced with #selector. For example:

    let sel: Selector = #selector(setter: UIScrollView.contentOffset)
    

    More details here