7

How can I create a Signal from a tap on a UIButton?

So far I tried to use target/action, but have come to think that there might be an easier way.

In an article of Colin Eberhardt, it is stated that Signals are appropriate for UI actions. But when I tried to make my around with target/action, I needed to create a CocoaAction was ultimately initialised with a SignalProducer.

What I want is some Signal that emits its next events with every user tap. I then want to transform this Signal to read from UITextFields and carry on those values to use them in my application.

Community
  • 1
  • 1
nburk
  • 22,409
  • 18
  • 87
  • 132

2 Answers2

8

Using convenience functions from this gist by @NachoSoto, I was able to achieve this quite simply with signalForControlEvents(UIControlEvents.TouchUpInside) :

self.startButton
      .signalForControlEvents(UIControlEvents.TouchUpInside)
      .map { _ in (self.name1TextField.text!, self.name2TextField.text!)}
      .observe { event in
          if let names = event.value {
              print("received names \(names)")
          }
       }
nburk
  • 22,409
  • 18
  • 87
  • 132
  • 1
    Looks good! You probably want to use `observeNext` though, since you're only interested in values (not completion, disposal, etc). – NachoSoto Dec 12 '15 at 02:43
4
 self.startButton
     .rac_signalForControlEvents(UIControlEvents.TouchUpInside)
     .subscribeNext { event in
         if let names = event.value {
            print("received names \(names)")
         }
     }
pcwang
  • 61
  • 3