Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 228
hendra Avatar asked Sep 28 '15 09:09

hendra


2 Answers

Since what you want is just another UIControlEvent, you can use (as you were before) the range defined by .applicationReserved as a free space for you to use. Though, a more correct and easy to use way to do this would be:

(Swift 3.0):

extension UIControlEvents {
    static var increased: UIControlEvents { return UIControlEvents(rawValue: 0b0001 << 24) }
    static var decreased: UIControlEvents { return UIControlEvents(rawValue: 0b0010 << 24) }
}

In this way you can easily use this definitions everywhere events are supposed to be used, also with the convenience of type inference (e.g. sendActions(for: [.valueChanged, .increased])).

The declaration also looks cleaner to me as being these bits it's easier to see that they're disjoint by using a shift. Since .applicationReserved is defined as 0b1111 << 24, it's more definite which parts of it you're using.

These can be public if needed, and there's not much difference between having computed vars like here or just assigning let constants.

like image 57
DeFrenZ Avatar answered Oct 04 '22 04:10

DeFrenZ


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)
like image 28
UditS Avatar answered Oct 04 '22 03:10

UditS