iosswiftcustom-controlsuser-interactionuicontrolevents

How to create a custom UIControlEvent in Swift?


I'm creating a custom UI-Element and want to trigger a custom UIControlEvent. I already found out, that there is a range ApplicationReserved.

Sadly this doesn't work, because it "does not conform to protocol 'RawRepresentable':

enum MyCustomEvents : UIControlEvents{
  case Increase = 0x01000000
  case Decrease = 0x02000000
}

Two questions:
1) Is this the right approach for custom events?
2) How can I define custom events correctly?

Thanks!


Solution

  • Since UIControlEvents are created as a struct of OptionSetType in Swift 2.0, you can create custom UIControlEvents in the same way.

    For your question, it will be

    struct MyCustomEvents : OptionSetType{
        let rawValue : UInt
    
        static let Increase = MyCustomEvents(rawValue: 0x01000000)
        static let Decrease = MyCustomEvents(rawValue: 0x02000000)
    }
    

    For adding a target/action to this custom UIControlEvent, you need to cast this as a UIControl Event.

    let controlEvent : UIControlEvents = UIControlEvents.init(rawValue: MyCustomEvents.Increase.rawValue)
    sliderControl.addTarget(self, action: "increaseAction:", forControlEvents: controlEvent)